absurd
absurd

Reputation: 331

g++ 4.7 strict-aliasing check invalid

When I compile the following code with g++ 4.7.

g++ -Wall -fstrict-aliasing 

I will get warning on the first cast:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]

The second cast is fine without any warning. Can any one help me understand why warning on the first cast ?

int main()
{
    char a [16];
    char * p = &a[0];

    //int i = *((int *)(&a[0])); //bad
    int j = *((int *)(p));  //ok
    return  0;
}

Upvotes: 4

Views: 180

Answers (1)

user743382
user743382

Reputation:

The second cast is fine without any warning. Can any one help me understand why warning on the first cast ?

That's not the question you should be asking. The question you should be asking is why the second cast doesn't display a warning, even though it's exactly as problematic as the first cast.

No warning is issued for (int *) p, because p could, based on its type, have been legitimately obtained by casting a pointer-to-int to char *. However, unless that is the case, dereferencing the result is still not allowed. Even if you don't get a warning.

Note that the warning is independent of the optimisations that could "break" your code. Your code could get a warning and work as intended. Your code could not get a warning and fail.

Upvotes: 4

Related Questions