[PATCH] C undefined behavior fix

dewar@gnat.com dewar@gnat.com
Fri Jan 4 14:36:00 GMT 2002


<<If you have an implementation-defined operation for turning a pointer into
an integer (and you must have such a rule as per the standard), you cannot
just make it undefined by claiming it is so when somebody does something
else with it.
>>

But the quoted paragraph is a part (a very important part) of the definition
of what the cast does in GCC. It is quite possible for an implementation to
say whatever it likes when something is implementation defined.

Implementation defined does not mean "do what I think it should do", it
means "do what the implementor decides to do", and the implementor will
tell you what has been decided.

It is entirely possible that some aspects of this implementation defined
behavior may give rise to undefined behavior. In this particular case, that
is EXACTLY what the gcc documentation is saying, and it is entirely reasonable
for it to do so (in fact it is hard to imagine that any C compiler would
do anything different).

Linus, the restrictions on what you can and cannot do with pointer arithmetic
are there for a reason (indeed for a series of very good reasons) in the
standard.

It is to me absurd to think that you can get around these restrictions in
arbitrary manner by doing 

  cast pointer to integer
  do integer arithmetic
  cast integer back to pointer

If the GCC documentation implies that this obviously unacceptable sequence
of operations is guaranteed to work, then the documentation needs fixing.
In fact it seems clear from the very clear quote, let's have it again:

<<  When casting from pointer to integer and back again, the resulting
  pointer must reference the same object as the original pointer, otherwise
  the behavior is undefined. That is, one may not use integer arithmetic
  to avoid the undefined behavior of pointer arithmetic as proscribed
  in 6.5.6/8.
>>

is saying in a crystal clear manner that the above sequence does NOT work.
You may object to the implementation decision here (personally I don't
see how any other decision is reasonable or possible), but you cannot
somehow say that the decision is improper according to the standard.

You talk about two wrongs making a right, but I don't see any wrongs or
rights here in the GCC rules, just a clear statement of what does and does
"work" given the implementation defined choices made by GCC.

The only thing that seems wrong is expecting code to work that the GCC
documentation clearly tells you is undefined.



More information about the Gcc mailing list