effect of free()

mcdonald at uxe.cso.uiuc.edu mcdonald at uxe.cso.uiuc.edu
Sat Sep 16 00:33:00 AEST 1989


In article <YZ3p34a00XcA04hUZt at andrew.cmu.edu> jdr+ at 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



More information about the Comp.lang.c mailing list