When I call malloc to allocate memory for a pointer which is local to a function ....

Q

When I call malloc to allocate memory for a pointer which is local to a function, do I have to explicitly free it?

✍: Guest

A

Yes. Remember that a pointer is different from what it points to. Local variablesare 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.

2016-03-31, 400👍, 0💬