free (NULL)

Richard Tobin richard at aiai.ed.ac.uk
Sat May 26 04:01:55 AEST 1990


In article <1724 at necisa.ho.necisa.oz> boyd at necisa.ho.necisa.oz (Boyd Roberts) writes:

>>There are plenty of cases where a careful programmer
>>might do "if(p) free(p)" with complete clarity and correctness.  

>I hope this `careful programmer' never uses malloc().  

Er, I hope they do.  Otherwise they're making a mistake in using free().

>If you allocate
>something, there comes a time when it should be free'd.  Not because
>it `might' be a good idea, but because it is correct to do so.

*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.

>free(NULL) has simplicity at the cost of clarity, correctness and portability.
>Successfully using an error return value is not a programming pearl.

If the NULL you pass to free was handed to you by malloc() than you
should almost certainly have already checked for it.  Even in this
case, it may simplify your error cleanup code if you just call free()
anyway.  But this wasn't one of the situations I had in mind.

-- Richard
-- 
Richard Tobin,                       JANET: R.Tobin at uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin



More information about the Comp.lang.c mailing list