This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Why does this code break strict-aliasing rules?
- From: Andrew Haley <aph at redhat dot com>
- To: Jonathan Lennox <jonathan at vidyo dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Thu, 12 Nov 2009 18:56:05 +0000
- Subject: Re: Why does this code break strict-aliasing rules?
- References: <6B55710E7F51AD4B93F336052113B85FE0549E@be150.mail.lan>
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.