Just a minor new twist on free()

Larry Hastings funkstr at ucscb.ucsc.edu
Mon Oct 1 10:25:13 AEST 1990



Seeing as how people are just now discussing using heap memory after it's
been free()d, I thought I'd suggest this.  It's something that either I or
my boss came up with (I forget who).  And, yes, the whole purpose of its
existence is to have a "side-effect", but this one is IMHO worth it:

#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.)

Just remember that this is a macro when you call it, and don't do anything
funny like smart_free(*x++), and those heap manager problems will go away.

This joins an entire brace of "smart_" functions (smart_calloc(),
smart_open(), smart_close() and so on) which act "intelligently".
This mainly means they call the function they replace (smart_write() calls
write()) and check the return value -- if there's anything wrong, they abort.
--
larry hastings, the galactic funkster, funkstr at ucscb.ucsc.edu

I don't speak for Knowledge Dynamics or UC Santa Cruz, nor do they speak for me

The 4th law of Robotics (courtesy of Lore Shoberg):
"A robot must encourage proper dental hygiene, except where such encouragement
 would interfere with the 0th, 1st, 2nd, and 3rd laws."



More information about the Comp.lang.c mailing list