Just a minor new twist on free()

Roger House roger at everexn.com
Tue Oct 2 04:29:27 AEST 1990


In <7365 at darkstar.ucsc.edu> funkstr at ucscb.ucsc.edu (Larry Hastings) writes:

>#define smart_free(x) { if (x != NULL) { free(x); x = NULL; } }

>This takes care of two problems:
>	1) If you access a pointer after smart_free()ing it, you are
>	   dereferencing a null pointer, which gives you a lovely error message
>	   (except on DOS, where I am doomed to stay).
>	2) If you smart_free() something twice, nothing bad happens.  (The
>	   pointer gets set to NULL the first time, and gets blocked by the
>	   "if" the second time.)

The ANSI C standard states that when the argument to free is a null pointer,
nothing happens.  So if your free function is ANSI, there is no need to check
for NULL to avoid calling free.

As for setting the pointer to NULL after freeing, I have done this for quite
some time, and it has quickly caught several bugs that could have turned into
nightmares.  However, I define a function, myfree, so I don't need to worry
about side-effects (the argument to the function is void **).  Another ad-
vantage of having a function is that then all heap operations are funneled
through a couple of my functions (mymalloc, myfree, myrealloc, etc.)  This
is very useful if you decide you want to do things like keep track of the
maximum amount of heap memory in use at a given time, etc.

Also, on occasion I use test versions of mymalloc and myfree which do things
like this:  my malloc saves all its return values in a table, and when myfree
is called it checks that the address of the space to be freed is in the table,
and then removes it from the table.  This mechanism has also saved me from
a few nasty heap bugs.

							Roger House



More information about the Comp.lang.c mailing list