effect of free()

Mark Brader msb at sq.sq.com
Wed Sep 20 11:40:37 AEST 1989


> >union pi {
> >    char *ptr;
> >    unsigned long num;
> >} x;
> >x.ptr = malloc(AMOUNT);
> >if (x.ptr != NULL) free(x.ptr);
> >foo(x.num);

> ... an implementation is entirely within its rights
> to generate a core dump when you try to execute it.

This assertion startled me, because I thought I knew everything that
the pANS (proposed Standard) says about integer types.  However, it's
true, and I thought I'd better point out why.

The pANS requires that integer types be represented in a pure binary
numeration system; a footnote, which I think is substantive and should
therefore have been in the main text, in effect amends this by saying
"except for the high bit which may mean anything" (thus allowing 2's
complement, 1's complement, etc.).

But while it thus almost-specifies the representation of each possible
value, it does NOT specify that all possible representations have to
correspond to values; only a minimal range of values is guaranteed to
exist for each type.  For instance, ints must include the values -32767
to +32767; there is no requirement that a 65536th distinct value be
supported.  So even on a 2's complement machine with 16-bit ints, the
bit pattern 0x8000 could legitimately be used for "undefined" instead
of for -32768 as usual, and an operation such as 1^0x8001 could
legitimately dump core.

It is for similar reasons that foo(x.num); could dump core.  The union
could have been used to load the unsigned long with a bit pattern not
legitimate for unsigned longs on that machine; such bit patterns may
exist if unsigned longs are longer than 32 bits.

(By the way, this is not true for characters.  The pANS in essence defines
a character as a byte-sized bit pattern, so no "undefined" one is allowed.)


-- 
Mark Brader, SoftQuad Inc., Toronto, utzoo!sq!msb, msb at sq.com
	A standard is established on sure bases, not capriciously but with
	the surety of something intentional and of a logic controlled by
	analysis and experiment. ... A standard is necessary for order
	in human effort.				-- Le Corbusier

This article is in the public domain.



More information about the Comp.lang.c mailing list