When I call malloc to allocate memory for a pointer which is local to a function, do I have to explicitly free it?
Yes. Remember that a pointer is different from what it points to. Local variables [footnote] are deallocated when the function returns, but in the case of a pointer variable, this means that the pointer is deallocated, not what it points to. Memory allocated with malloc always persists until you explicitly free it. (If the only pointer to a block of malloc’ed memory is a local pointer, and if that pointer disappears, there will be no way to free that block.) In general, for every call to malloc, there should be a corresponding call to free. 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 retur