Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

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

0
Posted

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

0

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

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123