Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!unmvax!aplcen!haven!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn) Newsgroups: comp.lang.c Subject: Re: effect of free() Message-ID: <11063@smoke.BRL.MIL> Date: 14 Sep 89 12:10:42 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> <11053@smoke.BRL.MIL> Reply-To: gwyn@brl.arpa (Doug Gwyn) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 44 In article jdr+@andrew.cmu.edu (Jeff Rosenfeld) writes: >union pi { > char *ptr; > unsigned long num; >} x; >x.ptr = malloc(AMOUNT); >if (x.ptr != NULL) free(x.ptr); >foo(x.num); >This is perfectly legal code (despite that x.num contains nothing of >guaranteed usefulness) ... No, it isn't. x.num has no value, and accessing it has indeterminate results. This is not a valid technique for converting pointers to corresponding integer representations; you must use a cast for that, and if you did use a cast, you still are accessing an invalid pointer value and should expect trouble. >and any compiler that generates code that causes >a seg fault on the call to foo() has some serious problems. I would say that any programmer who expects such code to work is the one who has problems. If you had written foo(x), then I would agree that that is legal, but still any attempt to use x.ptr (itself, not just what it points to) within foo would be "illegal" (i.e. not strictly conforming). It does show that the implementation would need to keep unions in generic data space, not in pointer space, but that was pretty obvious anyway. It is the loading of an address (pointer, offset, base, whatever) register that would trigger the trap. Getting back to your attempted example, referencing x.num would cause a data, not an address, register to be loaded in the kind of implementations we've been discussing. >Of course, if the ANSI committee deems my example illegal then I guess >it's time to find another language-of-choice. I don't speak for the committee, but speaking personally, feel free (maybe you should contact Herman Rubin and offer to help design a language you both can enjoy). >In the meantime, I'd appreciate if someone can prove by counter-example >using any real or imagined architecture that my claim is bogus. I've now seen at least four such examples posted in this newsgroup.