Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict aliasling warning on gcc 4.6.1 bug

I'm trying to compile the following on gcc with -pedantic-errors -pedantic -Wall -O2

#include <iostream>

void reset_uint32(uint32_t* pi)
{
    char* c = (char*)(pi);
    uint16_t* j = (uint16_t*)(c); // warning?
    j[0] = 0;
    j[1] = 0;
}

void foo()
{
    uint32_t i = 1234;
    reset_uint32(&i);
}

int main() {
   foo();
}

But I don't see any strict aliasing warnings. I have also tried to enable

-fstrict-aliasing
-Wstrict-aliasing

but still no warnings. Is it this a bug?

like image 569
user1086635 Avatar asked Dec 18 '11 17:12

user1086635


1 Answers

I rewrote your example to produce a warning about breaking the strict-aliasing rules:

void foo(int* pi) {
    short* j = (short*)pi;
    j[0] = j[1] = 0;
}

int main() {
    int i = 1234;

    foo(&i);

    short* j = (short*)&i;
    j[0] = j[1] = 0;
}

Even though, g++ 4.6 only shows the warning if you compile the code with -Wstrict-aliasing=2 instead of -Wstrict-aliasing. Also, it only shows the warning for the cast in main(), not in foo(). But I cannot see how/why the compiler would look at those two casts differently.

like image 83
fschoenm Avatar answered Oct 02 '22 18:10

fschoenm