Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

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.

An object shall have its stored value accessed only by an lvalue expression that has one of
the following types:

  • a type compatible with the effective type of the object,
  • a qualified version of a type compatible with the effective type of the object,
  • a type that is the signed or unsigned type corresponding to the effective type of the object,
  • a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
  • a character type.

...

Code Block
bgColor#FFCCCC
langc
short a[2];

a[0]=0x1111;
a[1]=0x1111;

*(int *)a = 0x22222222;  /* violation of aliasing rules */

printf("%x %x\n", a[0], a[1]);

...

When translating this code, an implementation can 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 can change with optimization level.

Implementation Details

Recent versions of GCC turn on the option -fstrict-aliasing (which allows alias-based optimizations) by default with -O2. Some architectures then print "1111 1111" as a result. Without optimization, the executable will generate the "expected" output "2222 2222".

...

ISO/IEC 9899:1999 Section 6.5, "Expressions"

Bibliography

...

[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. \[Acton 2006\] Mike Acton. [Understanding Strict Aliasing|http://www.cellperformance.com/mike_acton/2006/06/understanding_strict_aliasing.html]. June 01, Manual
[Walfridsson 2003] Krister Walfridsson. Aliasing, pointer casts and gcc 3.3 Aliasing issue. August, 2003.
[Acton 2006] Mike Acton. Understanding Strict Aliasing. June 01, 2006.

...

EXP38-C. Do not call offsetof() on bit-field members or invalid types      03. Expressions (EXP)      EXP40-C. Do not modify constant values