Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!cs.utexas.edu!uunet!yale!mfci!karzes From: karzes@mfci.UUCP (Tom Karzes) Newsgroups: comp.lang.c Subject: Re: effect of free() Message-ID: <1010@m3.mfci.UUCP> Date: 7 Sep 89 18:21:23 GMT References: <319@cubmol.BIO.COLUMBIA.EDU> <3756@buengc.BU.EDU> <1989Aug17.005548.745@twwells.com> <16022@vail.ICO.ISC.COM> <248@seti.inria.fr> Sender: karzes@mfci.UUCP Reply-To: karzes@mfci.UUCP (Tom Karzes) Organization: Multiflow Computer Inc., Branford Ct. 06405 Lines: 44 In article <248@seti.inria.fr> jourdan@minos.inria.fr (Martin Jourdan) writes: }>> char *ptr; }>> }>> ptr = malloc(1); }>> ... }>> free(ptr); }>> ... }>> if (ptr == 0) ... }>> }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. Nonsense. There are no indirect or indexed references in the code above, hence no opportunities for invalid address traps. Period. It might be invalid to attempt to dereference ptr, e.g., "if (*ptr == 0) ...", but no such attempt has been made in the code. If malloc returns 0x1000, then ptr contains 0x1000 and 0x1000 is a valid address. After the call to free, 0x1000 may no longer be a valid address, so *ptr may cause an invalid address trap. But ptr itself still contains 0x1000, and may be accessed regardless of whether or not 0x1000 is mapped, so long as 0x1000 is not dereferenced. }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. Sorry, but NULL is no more valid than the pointer returned by malloc. You are not allowed to dereference NULL (many machines do allow it, and return 0, but this merely fixes broken programs which do not proprtly guard against NULL pointers). The one thing you can count on is that NULL will compare unequal to any valid address, whereas your moldy old pointer may match some newly allocated address. But neither may be dereferenced.