Clarification on Gcc's strict aliasing rules

Segher Boessenkool segher@kernel.crashing.org
Sun Nov 7 04:10:00 GMT 2010


> I'm trying to understand what '-fstrict-aliasing' actually means.
>
> Looking at the man page, one can read:
>
>    -fstrict-aliasing
>        Allow the compiler to assume the strictest aliasing
>        rules applicable to the language being compiled.  For C
>        [...]
>
> What does "the strictest aliasing rules ..." means ?

It means the compiler is allowed to only guarantee behaviour that
the relevant standards guarantee, treat undefined behaviour as
undefined, etc.

> Also I don't really understand the examples provided by the man page. Ok
> type punning using union is still allowed.

It is allowed in C99, and a GCC extension for C90.  GCC guarantees
behaviour for it always, also with -fstrict-aliasing.

> But the second example which is:
>
>     However, this code might not:
>
> 		  int f() {
> 		    union a_union t;
> 		    int* ip;
> 		    t.d = 3.0;
> 		    ip = &t.i;
> 		    return *ip;
> 		  }
>
> _might_ not work. Why using 'might' ?

It isn't guaranteed to work.  It can work by accident.  A lot
of incorrect code sometimes works.

> Does it work or not ?

It isn't correct code.

> AFAIK, this type of aliasing is defined by the standard.

It is not.  You're accessing an object of type "double" using
an lvalue of type "int".  This is not ok; see C99 6.5/7.

> The third example is:
>
>     Similarly, access by taking the address, casting the
>     resulting pointer and dereferencing the result has
>     undefined behavior, even if the cast uses a union type,
>     e.g.:
>
> 		  int f() {
> 		    double d = 3.0;
> 		    return ((union a_union *) &d)->i;
> 		  }
>
> Again in my understanding of the standard, this is an undefined
> behaviour. So why does man page mention this case ?

Because it is a common misunderstanding.


Segher



More information about the Gcc-help mailing list