Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!gem.mps.ohio-state.edu!ginosko!uunet!mcsun!inria!seti!jourdan From: jourdan@seti.inria.fr (jourdan martin joseph) Newsgroups: comp.lang.c Subject: Re: effect of free() Message-ID: <248@seti.inria.fr> Date: 18 Aug 89 11:59:33 GMT References: <319@cubmol.BIO.COLUMBIA.EDU> <3756@buengc.BU.EDU> <1989Aug17.005548.745@twwells.com> <16022@vail.ICO.ISC.COM> Reply-To: jourdan@minos.inria.fr (Martin Jourdan) Organization: INRIA Rocquencourt, Le Chesnay, France Lines: 41 In article <16022@vail.ICO.ISC.COM> rcd@ico.ISC.COM (Dick Dunn) writes: >bill@twwells.com (T. William Wells) writes: >> ...For example, the following code fragment is nonportable: >> >> char *ptr; >> >> ptr = malloc(1); >> ... >> free(ptr); >> ... >> if (ptr == 0) ... >> >> The if might cause a trap when the value of ptr is accessed. > >Not true. The "if" only examines the value of the pointer, not what it >points to. You're wrong, Dick. Someone else already pointed it out, but let me make it clear again. Imagine a segmented memory architecture with protections, and imagine that the call to "free" above frees the last used block in the segment and that "free" is clever enough to determine it and decides to release the segment to the OS, thus making the whole segment invalid (this is perfectly conceivable, and not forbidden by any ``standard''; actually I'd love to see some programs/processes decrease their memory size when they no longer use it). Then merely loading the value of "ptr" in a register to test it against 0 will cause a invalid-address trap. The morale of the whole story is: DO NOT DO ANYTHING WITH A FREED POINTER. To make things safer, each time I free a pointer variable, the next statement is to copy some valid pointer value (usually NULL) into it. Of course, that does not solve the aliasing problem which was the basis of the whole discussion, but that alleviates many problems. Martin Jourdan , INRIA, Rocquencourt, France. My employers have no opinion and they guarantee my freedom of expression. -- Martin Jourdan , INRIA, Rocquencourt, France. My employers have no opinion and they guarantee my freedom of expression.