Casting does not work as expected when optimization is turned onModifying a variable through a pointer of an incompatible type can lead to unpredictable results. This is often caused by a violation of aliasing rules, which are part of the ISO C standard.
...
Code Block | ||
---|---|---|
| ||
#include <stdio.h> int main() { short a\[2\]; a[0]=0x1111; a[1]=0x1111; *(int *)a = 0x22222222; /* violation of aliasing rules */ printf("%x %x\n", a[0], a[1]); return 0; } |
The aliasing rules were designed to allow compilers more aggressive optimization. Basically, a compiler can assume that all changes to variables happen through pointers or references to variables of a type compatible to the accessed variable. Dereferencing a pointer that violates the aliasing rules results in undefined behavior and can be optimized out as follows.Optimized code produced by gcc.
Code Block | ||
---|---|---|
| ||
#include <stdio.h> int main() { short a\[2\]; a[0]=0x1111; a[1]=0x1111; printf("%x %x\n", a[0], a[1]); return 0; } |
Implementation Details
Wiki Markup |
---|
In the case above, the compiler may assume that no access through an integer pointer can change the array a, consisting of shorts. Thus, printf may be called with the original values of a\[0\] and a\[1\]. What really happens is up to the compiler and may change with architecture and optimization level. |
...
To disable optimizations based on alias-analysis for faulty legacy code, the option -fno-strict-aliasing can be used as a work-around. The option -Wstrict-aliasing (which is included in -Wall) warns about some - but not all - cases of violation of aliasing rules when -fstrict-aliasing is active.
Compliant Solution (gcc)
To fix the code above, you can use a union instead of a cast (note that this is a GCC extension which might not work with other compilers).
...