[PATCH] C undefined behavior fix

Linus Torvalds torvalds@transmeta.com
Fri Jan 4 16:07:00 GMT 2002


On Fri, 4 Jan 2002 dewar@gnat.com wrote:
> <<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.

Sure. Except is must say _something_. It must be defined behaviour. That's
what "implementation defined" means.

According to the standard,

	char c[10];

	(char *)((unsigned long)c) + 10)

is implementation-defined.

Also, according to the standard, implementation-defined means that a
conforming compiler has to document what it results in.

And it has to result in some pointer. It may not result in a pointer that
you can _dereference_, of course.

> 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.

It's not the gcc documentation that implies this, it is the C standard
that requires that a conforming compiler document what this does.

And it has to work (now, what _dereferencing_ the pointer does, that's
obviously a separate matter)

			Linus



More information about the Gcc mailing list