[PATCH] C undefined behavior fix
Richard Henderson
rth@redhat.com
Fri Jan 4 14:06:00 GMT 2002
On Fri, Jan 04, 2002 at 01:39:52PM -0800, Linus Torvalds wrote:
> The thing is, pointer expressions outside the area may be "undefined
> behaviour", but the same is NOT true if you cast the thing to an
> unsigned long or similar. At that point it is _implementation_ defined
> what the result is, and gcc has clear guidelines on what the
> int->pointer conversion is.
Indeed we do. Apparently you havn't read them. See
http://gcc.gnu.org/onlinedocs/gcc/Arrays-and-pointers-implementation.html
In particular,
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.
The primary reason for this restriction is that pointer arithmetic
becomes integer arithmetic the moment it enters rtl, at which point
we can't tell the difference between them anymore, and if we intend
to do any sort of alias analysis, we must be able to assume that
some sort of silliness isn't happening.
And before you object that you can't possibly write a kernel under
these restrictions, you should know that this basically only applies
to global variables. If you've got some object residing in the heap,
we don't know what the outer-most object really is, and so we can't
actually infer anything at all. But if I see "static int i[4];"
then dammit you are not going to access i[5] or i[5000000] no matter
what you say.
And that is exactly what's going on here, except that instead of a
user-declared array variable we have a string literal.
r~
More information about the Gcc
mailing list