Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!virtech!cpcahil From: cpcahil@virtech.uucp (Conor P. Cahill) Newsgroups: comp.lang.c Subject: Re: Just a minor new twist on free() Message-ID: <1990Oct01.020420.3401@virtech.uucp> Date: 1 Oct 90 02:04:20 GMT References: <7365@darkstar.ucsc.edu> Reply-To: cpcahil@virtech.UUCP (Conor P. Cahill) Organization: Virtual Technologies Inc., Sterling VA Lines: 35 In article <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). 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