Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ukma!xanth!mcnc!ecsvax!dukeac!bet From: bet@dukeac.UUCP (Bennett Todd) Newsgroups: comp.lang.c Subject: Re: What if I don't free() all my dynamically allocated memory? Keywords: On a Unix system, that is. Message-ID: <1384@dukeac.UUCP> Date: 2 May 89 19:52:48 GMT References: <2580@ssc-vax.UUCP> <386@nbires.nbi.com> Reply-To: bet@dukeac.UUCP (Bennett Todd) Organization: Radiology, Duke Med. Center, Durham, NC Lines: 30 In article <2580@ssc-vax.UUCP| dmg@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@orion.mc.duke.edu