I noticed the following code on Understanding Strict Aliasing:
uint32_t
swap_words( uint32_t arg )
{
U32* in = (U32*)&arg;
uint16_t lo = in->u16[0];
uint16_t hi = in->u16[1];
in->u16[0] = hi;
in->u16[1] = lo;
return (in->u32);
}
According to the author,
The above source when compiled with GCC 4.0 with the -Wstrict-aliasing=2 flag enabled will generate a warning. This warning is an example of a false positive. This type of cast is allowed and will generate the appropriate code (see below). It is documented clearly that -Wstrict-aliasing=2 may return false positives.
I wonder what is a false positive, and should I pay attention to it when aliasing variables?
Here is the "appropriate code (see below)" mentioned above, if it's relevant:
Compiled with -fstrict-aliasing -O3 -Wstrict-aliasing -std=c99
on GNU C version 4.0.0 (Apple Computer, Inc. build 5026) (powerpc-apple-darwin8),
swap_words:
stw r3,24(r1) ; Store arg
lhz r0,24(r1) ; Load hi
lhz r2,26(r1) ; Load lo
sth r0,26(r1) ; Store result[1] = hi
sth r2,24(r1) ; Store result[0] = lo
lwz r3,24(r1) ; Load result
blr ; Return
Here a "false positive" means that the warning is incorrect, i.e. that there is no problem here. False positive is a standard term in science and medicine, denoting an error in an evaluation process resulting in mistaken detection of a condition tested. (A false negative would be failure to emit a warning when one were appropriate.)
If you are sure that a warning is a false positive, you don't need to fix your code to remove it. You might still want to restructure the code to avoid compilation warnings (or turn off the warning for that section of code, if possible). A normally warningless compile ensures that, when a real warning appears, one you should pay attention to, you don't miss it.
false positive in general means when something pretends the answer is yes / conforms to some condition when actually it's not true.
So here gcc gives you a warning about incorrect cast from integer to structure of the same size holding two 16-bit integers because it's dangerous operation. But you know that it's actually correct and generates correct code.
gcc uses special heuristics to find problems with the strict aliasing rules. These heuristics can have wrong positives, situations where they report a warning but there isn't anything to report.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With