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

Matthew Meighan matt at nbires.nbi.com
Thu Apr 27 07:42:58 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!  
|
|  If I don't bother to free all of the memory I've dynamically
|  allocated in the tree structure, my program runs considerably
|  faster.
|
|  Anyway, I'm wondering if it's ok for me to just leave the freeing
|  out altogether.  Unix will free all of my resources for me anyway
|  right?  Is there any problem with doing this?

One solution would be to malloc blocks of memory large enough to
contain n structures apiece, where n is some resonable number for your
allocation.  You can use this as an array of structures and only call
malloc again when you have filled that block and need more structures.

This will reduce not only the number of calls to free, but the number
of calls to malloc.  The larger n is, the more this will spped up your
program.  And you can still free everything yourself instead of relying
on the OS to do it.  The trade-off, of course, is that you will usually
allocate more memory than you need.   But unless the structures are
really huge or memory exceptionally tight, this is usually not a big problem.


Matt Meighan          
matt at nbires.nbi.com (nbires\!matt)
-- 

Matt Meighan          
matt at nbires.nbi.com (nbires\!matt)



More information about the Comp.lang.c mailing list