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

Darin Johnson darin at nova.laic.uucp
Tue May 9 08:53:47 AEST 1989


>>I once programmed in an environment that did NOT, repeat NOT, automatically
>>free allocated heap memory when a program terminated.
>
>I certainly would *not* want any code of mine ported to an environment like
>that!  I am interested in
>porting to what is nice to use now, and what will be better in the future. I
>am not interested in porting to what I am glad we've outgrown.

The only thing that makes most OS's clear allocated memory on exit, is
virtual memory.  Without it, the OS will have to go to a lot of work to
keep track of the memory you allocated.  If you allocate averything off
of a stack, then it is no big deal, but what if you want to allocate something
that won't fit in your stack space?  Believe it or not, there are a lot
of machines that don't have virtual memory, or keep track of the memory
you allocate, or have a near infinite upper bound on the stack?  I believe
most small computers fall into this category, especially those that
multitask and/or support desktop thingies and stay resident thingies.
Not to mention embedded systems, etc.  I sure hope whoever programs
out missiles remembers to free all his memory.

Of course, you may have plenty of virtual space, but the real physical
space exists on whatever swap device you are using.  When that runs
out, the computer has no choice but to say "I can't figure out what memory
you are using and which is trash, so I'll just terminate your program
alltogether".  Also, don't expect the customers of your programs to be
able to agree with your recommended minimums of physical/swap space needed.
Not freeing memory will also tend to increase paging activity, since the
OS will be unable to re-use part of a page that you aren't using, and will
have to allocate another for you.

Note that there is a big difference between freeing memory on EXIT, and
freeing memory when you are done with it.  If you have a small program,
then it isn't as big a deal, and it is convenient not to worry about it,
but not very portable.

Darin Johnson (leadsv!laic!darin at pyramid.pyramid.com)
	We now return you to your regularly scheduled program.



More information about the Comp.lang.c mailing list