Interview Questions

I am allocating structures which contain pointers to other dynamically

C Interview Questions and Answers


(Continued from previous question...)

I am allocating structures which contain pointers to other dynamically

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.)

(Continued on next question...)

Other Interview Questions