Path: utzoo!attcan!uunet!nih-csl!lhc!mimsy!haven!udel!wuarchive!zaphod.mps.ohio-state.edu!mips!pacbell.com!pacbell!barn!everexn!roger From: roger@everexn.com (Roger House) Newsgroups: comp.lang.c Subject: Re: Just a minor new twist on free() Message-ID: <1990Oct1.182927.11186@everexn.com> Date: 1 Oct 90 18:29:27 GMT References: <7365@darkstar.ucsc.edu> Organization: Everex Systems, Inc. Lines: 32 In <7365@darkstar.ucsc.edu> funkstr@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