effect of free()

Doug Gwyn gwyn at smoke.BRL.MIL
Thu Sep 14 22:10:42 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) ...

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.



More information about the Comp.lang.c mailing list