Modifying a variable through a pointer of an incompatible type (other than unsigned char
) can lead to unpredictable results. Subclause 6.2.7 of the C standard mentions that two types may be distinct yet compatible, and addresses precisely when two distinct types are compatible.
This problem is often caused by a violation of aliasing rules. The C Standard, subclause 6.5, paragraph 7 [ISO/IEC 9899:2011], 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.
Accessing an object by means of any other lvalue expression (other than unsigned char
) results in
...
...
.
Noncompliant Code Example
...