[PATCH] C undefined behavior fix
Florian Weimer
fw@deneb.enyo.de
Sat Jan 5 11:46:00 GMT 2002
Linus Torvalds <torvalds@transmeta.com> writes:
>> [#6] Any pointer type may be converted to an integer type.
>> Except as previously specified, the result is
>> implementation-defined. If the result cannot be represented
>> in the integer type, the behavior is undefined. The result
>> need not be in the range of values of any integer type.
>>
>> A less verbose version is: "Any pointer type may be converted to an
>> integer type, and the behavior is undefined."
> You somehow magically dropped the conditional.
The magic is quite simple: An implementor is free to decide which
pointer values can be represented in integer types, and this set of
values can be empty in a conforming implementation.
> And that conditional is very very important.
Yes, it is crucial for your argument. ;-)
> Guess what? Gcc has a _warning_ for when the conditional happens. It's
> called
>
> warning: cast from pointer to integer of different size
>
> and it's a warning when you invoce the undefined behaviour rather than the
> implementation-defined one.
This warning is also issued when you converted a 32 bit pointer to a
64 bit integer, so I doubt it has been constructed to specifically
warn about the undefined behavior in 6.3.2.3(6). And by the way, the
warning does not read "pointer value not representable in integer".
> And people who know what the implementation is (and can read plain
> english) know that a 32-bit pointer can be represented perfectly well in a
> 32-bit integer as on normal architectures.
It *can* be represented, in *one* particular implementation, but this
does not mean that all pointer values *must* be representable for
*all* implementations.
> You also do not seem to realize that C is a unique language: it's a
> mid-level langauge with a number of fairly high-level features, but it is
> also able to do low-level stuff.
Standard C has neither a concept of machine addresses, nor does the
standard require a uniform, linear address space.
(There is no requirement in the C standard that pointers behave like
machine addresses. For example, there are cases in which two pointers
to objects of the same type satisfy p == q (because the objects are
identical), but p + 2 is undefined according to the standard, and
q + 2 is not.)
> And that's exactly WHY the standard notes the fact that the
> conversion is supposed to be consistent with the addressing mode of
> the machine.
Linus, you are hallucinating. There is no such requirement in the
standard. The standard does not even define something which comes
close to "the addressing mode of the machine", this is completely
beyond the scope of the standard.
More information about the Gcc
mailing list