[vox-tech] Must one free() in C?

Mark K. Kim vox-tech@lists.lugod.org
Wed, 8 May 2002 15:24:07 -0700 (PDT)


On Wed, 8 May 2002, Jeff Newmiller wrote:

> On Wed, 8 May 2002, Mark K. Kim wrote:
>
> [...]
>
> > The impliciation of requiring calls to free() before
> > exitting is enormous -- one would have to keep track of all the allocated
> > memory before exitting from any error condition!
>
> Are you complaining? :)

If I understand you correctly, one must call free() on all allocated
memory before exitting the program.  That means you can't exit simply
because you ran out of memory because first you must *free* all memory
first;  you can't exit because of a failed assertion test -- because first
you must free all memory first; and you can't exit from a program because
you got a signal that can't be handled any further -- because you first
must free all memory first!  That's rediculous!

If the above is true, I think the better question is "why aren't *you*
complaing?"

The system (whether that be the OS or the C library) obviously knows of
all its memory and how they're allocated; if it didn't, free() wouldn't
know how much memory to free when you call free() on a pointer.  So it's
got a list of allocated memory *somewhere*, so why can't *it* handle
freeing all the memory upon exit?  If freeing memory is *required*, then
the system, designed to make the programmers' lives easier, should be the
one doing the freeing, not the programmer!

If what you're saying is true, I'd be writing malloc(), calloc(), and
realloc() wrappers -- the ultimate set of functions that keeps track of
all the allocated memory and calls itself on exit() (using atexit()) to
free all memory.  That's very generic, it's platform-independent, and
there's no more or less overhead than a specialized one (for the most
part).  The question then is, why doesn't the C standard say this easy
thing can't be implemented by the system and has to be implemented by the
programmer?

--
Mark "Jeff's-gotta-be-wrong" Kim
[homepage address removed in fear for personal safety]
PGP key available upon request to only closest relatives.