Re: Strict aliasing violation?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 11 September 2012 16:06, Marc Glisse <marc.glisse@xxxxxxxx> wrote:
> On Tue, 11 Sep 2012, Jonathan Wakely 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.  Can the optimisers still cause this code to
>> do unexpected things, even though the diagnostic is absent?
>
>
> I thought char was the type that can alias anything (so the optimizer stays
> clear).

Only in one direction.  [baic.lval]/10 says you can access an int
object through a glvalue of char or unsigned char type, but not vice
versa.  In my example the object being accessed has type char[1024]
and it is accessed through a glvalue of type int.

Or are you saying both pieces of code are valid, and the diagnostic is wrong?

Because I believe the first has undefined behaviour, and my question
is whether the second is still undefined but the diagnostic is
missing, or if the trivial transformation to introduce a char*
variable is sufficient to make it valid.


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux