free (NULL);

bdm659 at csc.anu.oz bdm659 at csc.anu.oz
Wed May 9 23:13:44 AEST 1990


In article <1194 at wet.UUCP>, noah at wet.UUCP (Noah Spurrier) writes:
>
> Is there anything wrong with freeing a NULL? pointer? I have a function that
> uses a static pointer. Everytime the function is called it frees up the
> previous pointer using free, but the first time the function is called
> there is nothing to free; the static pointer is initialized to NULL.

The ANSI standard says that free() is a no-op if the argument is null.
Many older libraries treat it like that too, but some don't.  Use
something like   if (p != NULL) free(p)  if you want maximum portability.
The extra overhead would be trivial.

Incidentally, the exact form  free(NULL)  is dangerous is there is no
visible prototype for free().  If you really want to pass a null pointer,
use  free((void*)NULL)  or  free((char*)NULL).  The same holds true for
procedures other than free(), of course.   (In general you must cast NULL
to a pointer of the type expected by the procedure, unless there is a
prototype which will cause this cast to be done for you.)  Failure to do
this cast is a quite common programming error.

Brendan McKay.   bdm at anucsd.anu.oz.au  or  bdm at csc.anu.oz.au



More information about the Comp.lang.c mailing list