scope of malloc

Doug Gwyn gwyn at smoke.brl.mil
Wed Nov 7 23:12:23 AEST 1990


In article <1791 at sirius.ucs.adelaide.edu.au> mferrare at adelphi.ua.oz.au (Mark Ferraretto) writes:
>	When malloc is called in a function and the scope of the pointer is
>only that function is the memory deallocated when the pointer is (ie on exit
>of the function?) deallocated?  Or does that chunk of memory hang around util
>the program terminates?

The storage remains allocated until explicitly free()d or the program
terminates, whichever occurs first.  It would be truly horrible if the
storage were deallocated based on dynamic scoping as you suggest; that
would make it very hard to construct elaborate data structures, since
you'd have to do all the allocation within the same function that uses
the structure.

>I am calling several functions that involve a lot of
>dynamic memory allocation most of which is only relevant to the scope of the
>function where the memory is allocated.  These functions get called repeatedly.
>So do I need to fill these functions to include free() calls with at the end
>of each function?

Yes, or if you can simply declare them as auto variables they'll be cleaned
up for you.

>Please e-mail to me as I don't usually read this newsgroup.

Too bad.



More information about the Comp.lang.c mailing list