Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uwm.edu!bionet!agate!darkstar!ucscb.UCSC.EDU!funkstr From: funkstr@ucscb.ucsc.edu (Larry Hastings) Newsgroups: comp.lang.c Subject: Just a minor new twist on free() Message-ID: <7365@darkstar.ucsc.edu> Date: 1 Oct 90 00:25:13 GMT Sender: usenet@darkstar.ucsc.edu Organization: Knowledge Dynamics Corporation Lines: 32 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@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."