prev up next   top/contents search

comp.lang.c FAQ list · Question 7.23

Q: I'm allocating structures which contain pointers to other dynamically-allocated objects. When I free a structure, do I also have to free each subsidiary pointer?

A: Yes. malloc knows nothing about structure declarations or about the contents of allocated memory; it especially does not know whether allocated memory contains pointers to other allocated memory. In general, you must arrange that each pointer returned from malloc be individually passed to free, exactly once (if it is freed at all).

A good rule of thumb is that for each call to malloc in a program, you should be able to point at the call to free which frees the memory allocated by that malloc call. (In many cases, you'll free blocks of memory in the reverse order you allocated them, although this order is by no means required.)

See also question 7.24.

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

Hosted by Eskimo North