Just a minor new twist on free()
Conor P. Cahill
cpcahil at virtech.uucp
Mon Oct 1 12:04:20 AEST 1990
In article <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).
Only if you use the same pointer. If the pointer had been copied somewhere
else (or a pointer within that area had been used) it still would point
to the area that had been freed.
> 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.)
I don't think you should do this. If you are calling free twice with the
same pointer, something is wrong. I would prefer an abort, so people could
track down the problem, not hide it.
A while back I put together a debugging library for malloc and it's
associated functions which was posted to comp.sources.unix back in may/june.
This library purposely trashes data pointed to by the free'd pointer to
ensure that you aren't using a freed pointer (in addition to lots
of other checks, like overrunning the amount of malloc data that you
asked for).
If you are working with malloc'd data, you might want to get a copy of
the library. It makes solving most malloc problem easy.
--
Conor P. Cahill (703)430-9247 Virtual Technologies, Inc.,
uunet!virtech!cpcahil 46030 Manekin Plaza, Suite 160
Sterling, VA 22170
More information about the Comp.lang.c
mailing list