Strict aliasing violation?
Ian Lance Taylor
iant@google.com
Tue Sep 11 16:20:00 GMT 2012
On Tue, Sep 11, 2012 at 8:00 AM, Jonathan Wakely <jwakely.gcc@gmail.com> wrote:
> G++ correctly warns about a strict aliasing violation in this code,
> because an object of type char is accessed as type uintptr_t:
>
> char buf[64];
> inline int get(int offset)
> {
> return *reinterpret_cast<int*>(&buf[offset]);
> }
>
> $ g++-4.7 f.cc -c -fstrict-aliasing -Wstrict-aliasing
> f.cc: In function 'int get(int)':
> f.cc:4:48: warning: dereferencing type-punned pointer will break
> strict-aliasing rules [-Wstrict-aliasing]
>
> But the following doesn't elicit a warning:
>
> char buf[64];
> inline int get(int offset)
> {
> char* addr = &buf[offset];
> return *reinterpret_cast<int*>(addr);
> }
>
> I believe this code is still undefined, for exactly the same reason,
> but I assume the diagnostic machinery isn't smart enough to detect the
> violation of the rules.
Yes. That is a frontend warning that triggers only on typecasts that
are clearly invalid. A typecast from char* to int* is not clearly
invalid.
> Can the optimisers still cause this code to
> do unexpected things, even though the diagnostic is absent?
Yes. You may get a warning at -Wstrict-aliasing=3.
Ian
More information about the Gcc-help
mailing list