Why does this code break strict-aliasing rules?

Andrew Haley aph@redhat.com
Thu Nov 12 18:56:00 GMT 2009


Jonathan Lennox wrote:

> I have some code which is giving strict-aliasing warnings on gcc 4.4.1,
> and I don't understand why.
> 
> When I compile alias-warning2.c (attached), I get
> 
> $ gcc -O2 -Wall alias-warning2.c -o alias-warning2
> alias-warning2.c: In function 'main':
> alias-warning2.c:31: warning: dereferencing pointer 'd2.16' does break
> strict-aliasing rules
> alias-warning2.c:39: note: initialized from here
> 
> and indeed, when I run, gcc has optimized out the offending code:
> 
> $ ./alias-warning2
> Aliasing is unhappy!  d2.base.a == 5
> 
> However, as far as I can tell, at line 31 the object d2.base (which has
> type 'struct base') is indeed being accessed through a pointer of type
> 'struct base*'.
> 
> If I change the inline function to take the type 'struct base*'
> directly, rather than 'union derived_union*', I do not get a warning, or
> mis-compilaton.
> 
> Am I missing something, or is gcc mis-compiling correct code?

The development version of gcc doesn't give this warning.  I think it's
partly a matter of how much inlining gets done, and how far gcc sees through
the type casts.

However, I think you're misunderstanding the standard.  Here is Section
6.3.2.3, Pointers:

"A pointer to an object or incomplete type may be converted to a
pointer to a different object or incomplete type. If the resulting
pointer is not correctly aligned for the pointed-to type, the
behavior is undefined. Otherwise, when converted back again, the
result shall compare equal to the original pointer."

That's all.  You can compare the result with the original pointer.
If that doesn't work, we have a bug.

Andrew.



More information about the Gcc-help mailing list