prev up next   top/contents search

comp.lang.c FAQ list · Question 7.20

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


A: 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(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
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


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North