Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!pt.cs.cmu.edu!andrew.cmu.edu!jdr+ From: jdr+@andrew.cmu.edu (Jeff Rosenfeld) Newsgroups: comp.lang.c Subject: Re: effect of free() Message-ID: Date: 12 Sep 89 21:40:50 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> Organization: Carnegie Mellon, Pittsburgh, PA Lines: 48 In-Reply-To: <248@seti.inria.fr> > Excerpts from netnews.comp.lang.c: 18-Aug-89 Re: effect of free() > jourdan m. joseph@seti.i (1729) > >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. I can't believe this went so long without a response. Dick is correct; @i[you] are mistaken, Jourdan. Keep in mind that pointers are stored in memory just like any other data types and can be loaded into general-purpose registers. No architecture of which I am aware does protection checking when loading data into a general purpose register. Similarly, the only segemented architecture with which I am familiar (80*86) does even allow any operations on segment registers save load, push, and validate (or some such). In other words, there is no fear of protection violation (even with a segemented architecture) until you attempt to dereference a pointer. The key is that with segments, dereferencing begins by loading a segement register. Get it? BTW, the "non-portable" code given is unlikely to work in any event because if the malloc() call fails then you're calling free(NULL) which is very likely to cause a seg fault in any protected environment. - Jeff.