### Question 7.20

You can't use dynamically-allocated memory after you free it, can you?

No. Some early documentation for `malloc` stated that the contents of freed memory were ``left undisturbed,'' but this ill-advised guarantee was never universal and is not required by the C Standard.

Few programmers would use the contents of freed memory deliberately, but it is easy to do so accidentally. Consider the following (correct) code for freeing a singly-linked list:

    	struct list *listp, *nextp;
    	for(listp = base; listp != NULL; listp = nextp) {
    		nextp = listp->next;
    		free((void *)listp);
    	}

and notice what would happen if the more-obvious loop iteration expression `listp = listp->next` were used, without the temporary `nextp` pointer.

References: K&R2 Sec. 7.8.5 p. 167
ANSI Sec. 4.10.3
ISO Sec. 7.10.3
Rationale Sec. 4.10.3.2
H&S Sec. 16.2 p. 387
CT&P Sec. 7.10 p. 95

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback