free (NULL)

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Sat May 26 19:14:05 AEST 1990


In article <2574 at skye.ed.ac.uk>, richard at aiai.ed.ac.uk (Richard Tobin) writes:
> *Sigh*  Yes, *if* you allocate something, you probably want to free it
> later.  But what if you *didn't* allocate it?  Then you *don't* want
> to free it.

> It's completely reasonable, for example, to have a structure with fields
> that might either be filled in (with a string containing a name, perhaps)
> or be null (because the name isn't known, perhaps).  In such a case, when
> you free the structure, "if(s->name) free(s->name)" is exactly what you
> need to do.

Let me change the emphasis on that, from
	"what if you *didn't* allocate it?"
to
	"what if *you* didn't allocate it?"

The problem I've often had is that I have a data structure containing
some pointers, and *I* have filled some of them in (using strdup())
and the caller preset some of them to defaults.  Now I'm going to change
one of them.  Should I free it?  If *I* allocated it, certainly, there
isn't any other copy of the pointer.  If the *caller* allocated it
*and* the caller hasn't any other copy of the pointer *and* it was
allocated using malloc() then it would be a good idea to free it, but
if	-- the caller wants to keep it
or	-- it was a string literal
or	-- it came from something other than malloc()
then it should _not_ be given to free(), and checking for NULL isn't
going to help me.  I've been driven to two extremes, neither of which
I am happy with:

Method 1:	play safe and _don't_ free things when there's any doubt.
Advantage:	I'm never going to free anything I shouldn't.
Problem:	I'm never going to free things I _should_, storage leak!

Method 2:	add an extra field beside each pointer saying "it is safe
		to free this pointer".
Advantage:	I get to free _precisely_ what needs freeing (and NULL is
		not a special case; it gets the "not safe to free" flag).
Problem:	the caller has to preset the fields; it is easy to forget
		this or to remember it and get it wrong.

(Method 3, of course, would be to use a garbage collector, and I have one
somewhere that came over the net.  But I'd rather not make my programs any
less portable than I have to.  Method 4 would be to use a fast safe language
like SML, except that I haven't actually got enough memory to run it and it
doesn't actually work on this machine.)

Note that the free(NULL) kluge doesn't help with this one tiny little bit.

Can anyone suggest a better way of tackling this problem in portable C?

-- 
"A 7th class of programs, correct in every way, is believed to exist by a
few computer scientists.  However, no example could be found to include here."



More information about the Comp.lang.c mailing list