Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ames!haven!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn) Newsgroups: comp.lang.c Subject: Re: The free() thing Message-ID: <11089@smoke.BRL.MIL> Date: 17 Sep 89 00:28:41 GMT References: <1989Sep14.022055.5961@twwells.com> <7513@bunker.UUCP> Reply-To: gwyn@brl.arpa (Doug Gwyn) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 44 In article <7513@bunker.UUCP> garys@bunker.UUCP (Gary M. Samuelson) writes: >I disagree. For purposes of debugging, I have written my own >functions to call malloc() and free(). Mymalloc() calls malloc() >and records the pointer returned. Myfree() checks to make sure that >(1). the pointer I want to free() was one originally obtained by >mymalloc(), and (2) that it has not already been released by myfree(). >I claim that this is a valid use for a pointer which no longer points >to anything. I too have implemented such a safety-checking malloc/free wrapper, and it seems to me that yours must be making a mistake. You should be checking only that the pointer fed to myfree() is one CURRENTLY HANDED OUT by myalloc(), not that it has never previously been fed to myfree(). As you malloc/free/malloc/free/..., eventually the same pointer values come around again. Having been previously freed does not mean that a pointer value is not currently being used correctly, because it may have been returned by a subsequent malloc(). The safety-checking malloc/free wrapper will not work portably IF in fact there is pointer abuse, because of the inability to safely inspect invalid pointer values in some environments. It will work in all environments so long as no pointer abuse occurs. Thus it is handy for debugging applications in an environment where invalid pointers are safe to inspect, later porting the debugged application to a more fussy environment. >But even so, suppose there was another copy of that same pointer >in another variable? How will the compiler know about that one? It can't. The example this is a response to was misleading. >As someone else has said, some day there will be two kinds of C >compiler: standard-conforming, and useful. It was an equally stupid thing for someone else to have said. The Standard does not require that an implementation prevent you from looking at invalid pointer values. It merely permits C implementations FOR WHICH THAT IS THE NATURAL BEHAVIOR to do so. Those implementations probably would have done so in the absence of a C standard. Your assumption that it is safe to inspect an invalid pointer is nonportable. That has nothing to do with the proposed Standard.