Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!uxc.cso.uiuc.edu!uxc.cso.uiuc.edu!ux1.cso.uiuc.edu!uxe.cso.uiuc.edu!mcdonald From: mcdonald@uxe.cso.uiuc.edu Newsgroups: comp.lang.c Subject: Re: effect of free() Message-ID: <225800221@uxe.cso.uiuc.edu> Date: 15 Sep 89 14:33:00 GMT References: <246@ssp1.idca.tds.philips.nl> Lines: 56 Nf-ID: #R:ssp1.idca.tds.philips.nl:-24600:uxe.cso.uiuc.edu:225800221:000:2204 Nf-From: uxe.cso.uiuc.edu!mcdonald Sep 15 09:33:00 1989 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) ... Doug Gwyn replies: >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. I don't think that "illegal code" should apply to the example. It should be "implementation defined behaviour". It is clearly not portable. But somewhere there has to be a way to diddle the bits in objects that are not integers (where of course there are the legal & and | operators. Somebody, somewhere has to be able to diddle the bits in a double or float, in order to construct it out of an integer double d; int i; ...... d = i; and somebody has to diddle the bits in a pointer (on machines with segments or read-write-execute bits stuck onto pointers) when it is created (by malloc or the OS). One can diddle bits in pointers by using integer types and then casting to pointers, but doing it in float types requires unions - because casting an integer type to a float type preserves the VALUE, not the bits. Why would someone want to construct a float themselves, rather than casting? Well, perhaps they desire to construct an illegal value (i.e. IEEE float format NaN). This might occur inside a floating exception handler, or a math routine ( sqrt(-6) ). Perhaps some might say "do it in assembler", but sometimes I would like to do it in C. When I say "somebody" I am including explicitly the routines in the OS that pass pointers to "malloc". If this sort of stuff is not literally IMPOSSIBLE on a given machine, using a union should work. If it IS impossible - don't buy the machine. If it doesn't work - don't buy the compiler. Is not most of Unix written in C? Doesn't this sort of stuff happen there? Doug McDonald