Modifying a variable through a pointer of an incompatible type (other than unsigned char
) can lead to unpredictable results. This is often caused by a violation of aliasing rules. The C Standard, Section 6.5, para. 7 [ISO/IEC 9899:2011], specifies those circumstances in which an object may or may not be aliased.
...
Accessing an object by means of any other lvalue expression (other than unsigned char
) results in undefined behavior . See undefined behavior 34 of in Annex J of the C Standard.
Noncompliant Code Example
...
However, instead of reading directly from union member, it assigns a pointer ip
to reference the integer value and returns the value referenced by the pointer. Unfortunately, this is a violation of the strict aliasing rules, and in this case the compiler may determine that ip
refers to some value other value than the value stored by t.i
and return a value other than the expected value.
...
In this noncompliant code example, access by taking the address, casting the resulting pointer, and dereferencing the result has undefined behavior, even if the cast uses a union type.
...
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 generates 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.
...
This code example now reliably outputs "2222 2222.".
Risk Assessment
Optimizing for performance can lead to aliasing errors which that can be quite difficult to detect. Furthermore, as in the preceding example, unexpected results can lead to buffer overflow attacks and/or bypassing security checks and/or unexpected execution.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP39-C | medium | unlikely | high | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
PRQA QA-C |
| 0310 3305 | Partially implemented |
Related Guidelines
ISO/IEC TR 17961 | (Draft) Accessing an object through a pointer to an incompatible type [ptrcomp] |
---|
Bibliography
[Acton 2006] | "Understanding Strict Aliasing" |
GCC Known Bugs | "C bugs, Aliasing |
---|
...
Issues while |
---|
...
Casting to Incompatible Types" | |
---|---|
GCC Manual | |
[ISO/IEC 9899:2011 |
...
] | Section 6.5, "Expressions" |
[Walfridsson 2003] |
...
...
...
Aliasing issue. August, 2003.
[Acton 2006] Mike Acton. Understanding Strict Aliasing. June 01, 2006.