I'm trying to check some of my code for strict aliasing violations, but it
looks like I've missed something while trying to understand the strict aliasing
rule.
Imagine the following code:
#include <stdio.h>
int main( void )
{
unsigned long l;
l = 0;
*( ( unsigned short * )&l ) = 1;
printf( "%lu
", l );
return 0;
}
Classic and basic example. With GCC 4.9 (-Wall -fstrict-aliasing -Wstrict-aliasing -O3
), it actually reports the error:
dereferencing type-punned pointer will break strict-aliasing rules
But the following compiles fine:
#include <stdio.h>
int main( void )
{
unsigned long l;
unsigned short * sp;
l = 0;
sp = ( unsigned short * )&l;
*( sp ) = 1;
printf( "%lu
", l );
return 0;
}
In my understanding, the second example also violates the struct aliasing rule.
So why does it compile? Is it an accuracy issue in GCC, or have I missed
something with strict aliasing?
I also found the following topic: Why are no strict-aliasing warnings generated for this code?
Compiling with -Wstrict-aliasing=2
or -Wstrict-aliasing=3
makes no difference.
But -Wstrict-aliasing=1
does report the error on the second example.
GCC documentation says level 1 is the least accurate, and can produce a lot
of false positives, while level 3 is the most accurate...
So what's happening here? An issue with my own understanding or an issue with GCC?
Bonus question
I usually prefer Clang/LLVM over GCC for my projects, but it seems Clang
doesn't issue any warning about strict aliasing.
Does anyone knows why?
Is it because it is not able to detect violations, or because it does not follow
the rule when generating code?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…