What if I don't free() all my dynamically allocated memory?

Bennett Todd bet at dukeac.UUCP
Wed May 3 05:52:48 AEST 1989


In article <2580 at ssc-vax.UUCP| dmg at ssc-vax.UUCP (David Geary) writes:
> I'm writing some code where I use some home-grown functions to
> create, manipulate and destroy a tree of "generic" structures.
> (Each object in the tree is dynamically allocated using malloc())
>
> The last thing I do in the program is to free every object in
> the tree.
>
> After running prof on the executable, I found that almost half
> my time was spent in _free!  

malloc() and free() are a heap managament system, to provide a convenient and
portable interface between yourself and whatever memory allocation scheme the
native OS offers (under UNIX it is done with brk() and sbrk() and like that, I
believe; I've never bothered looking under the hood of malloc()). I think most
OS memory management schemes look more like a stack than like a heap, but in
any case, regardless of what malloc() is running on top of, the resources it
allocates should be freed just fine upon exiting the program. If they weren't,
many common programming errors would crash the system very quickly. 

I never bother calling free, unless I have a system that could be creating and
tearing down variable sized objects all day long. If I am working with only a
limited number of possible sizes, I make my own allocators that work with a
linked free list for each type (grabbing more memory from malloc when
necessary, in big blocks, and returning free memory to a linked list rather
than the malloc/free heap). This runs extremely fast. If your program never
needs to reuse memory, then you don't need to worry about freeing at all.

-Bennett
bet at orion.mc.duke.edu



More information about the Comp.lang.c mailing list