effect of free()

Alan J Rosenthal flaps at dgp.toronto.edu
Fri Sep 15 04:54:20 AEST 1989


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) and any compiler that generates code that causes
>a seg fault on the call to foo() has some serious problems.

Well, without agreeing that it's legal code (can't there be invalid int values
as well as invalid pointer values?%), I would like to point out that x.num == 0
may not be the same as x.ptr == NULL, even if null pointers are represented by
all bits zero.

Suppose pointers are 48 bits and int and long are both 32 bits.  Then x.num
might be only the high or only the low 32 bits of the pointer's representation.
These might all be zero even if the pointer is not all zero.

So, wrt the previous discussion about loading pointer values into address
registers, it might not be possible to load pointer values into data registers
because they might not fit.

ajr

% in other words, can "int x; printf("%d\n", x);" dump core?  I would think
it could.  If it couldn't, that would be bad, because then environments which
caused an abort in this situation wouldn't be ansi-compliant, and I think that
aborting on the access of undefined values can be useful for debugging.



More information about the Comp.lang.c mailing list