Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!ncar!ico!nbires!matt From: matt@nbires.nbi.com (Matthew Meighan) 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: <386@nbires.nbi.com> Date: 26 Apr 89 21:42:58 GMT References: <2580@ssc-vax.UUCP> Organization: NBI Inc, Boulder CO Lines: 39 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! | | 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@nbires.nbi.com (nbires\!matt) -- Matt Meighan matt@nbires.nbi.com (nbires\!matt)