Wiki Markup |
---|
Modifying a variable through a pointer of an incompatible type can lead to unpredictable results. This is often caused by a violation of aliasing rules. C99, Section 6.5, paragraph 7 \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] specifies those circumstances in which an object may or may not be aliased. |
...
The programmer in this noncompliant code example is attempting to read from a different union member than the one most recently written to (called ; this is known as "type-punning." ).
Code Block | ||
---|---|---|
| ||
union a_union { int i; double d; }; int f() { a_union t; int *ip; t.d = 3.0; ip = &t.i; return *ip; } |
...
Wiki Markup |
---|
When translating this code, an implementation maycan assume that no access through an integer pointer can change the array {{a}}, consisting of shorts. Consequently, {{printf()}} may be called with the original values of {{a\[0\]}} and {{a\[1\]}}. The actual behavior is implementation-defined and maycan change with optimization level. |
...
Recent versions of GCC turn on the option -fstrict-aliasing (which allows alias-based optimizations) by default with -O2. And some Some architectures then print "1111 1111" as a result. Without optimization, the executable will generate the "expected" output "2222 2222".
To disable optimizations based on alias-analysis for faulty legacy code, the option -fno-strict-aliasing can be used as a workaround. The option -Wstrict-aliasing (which is included in -Wall) warns about some - ,but not all - , violations of aliasing rules when -fstrict-aliasing is active.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP39-C | medium | unlikely | high | P6 | L2 |
Related Guidelines
ISO/IEC 9899:1999 Section 6.5, "Expressions"
Bibliography
Wiki Markup |
---|
[GCC Known Bugs|http://gcc.gnu.org/bugs.html#known] C bugs, Aliasing issues while casting to incompatible types [GCC Manual|http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Optimize-Options.html#Optimize-Options] \[Walfridsson 2003] Krister Walfridsson. [Aliasing, pointer casts and gcc 3.3|http://mail-index.netbsd.org/tech-kern/2003/08/11/0001.html] Aliasing issue. August, 2003. \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.5, "Expressions" \[Acton 2006\] Mike Acton. [Understanding Strict Aliasing|http://www.cellperformance.com/mike_acton/2006/06/understanding_strict_aliasing.html]. June 01, 2006. |
...