...
These rules say that a program is invalid if you try to access a variable through a pointer of an incompatible type. This is happening in the following example where a short is accessed through a pointer to integer (the code assumes 16-bit shorts and 32-bit intsintegers).
Noncompliant Code Example
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.
...
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).
Code Block | ||
---|---|---|
| ||
\#include <stdio.h> int main() { union { short a\[2\]; int i; } u; u.a\[0\]=0x1111; u.a\[1\]=0x1111; u.i = 0x22222222; printf("%x %x\n", u.a\[0\], u.a\[1\]); return 0; } |
Now the result will always be "2222 2222".
Risk Assessment
Unauthorized modifications to public static variables can result in unexpected behavior and can bypass important Optimizing for performance can lead to such aliasing errors which can be quite difficult to detect. Furthermore as in the case above unexpected results can lead to buffer overflow attacks and/or bypassing security checks and/or invoke malicious codeunexpected execution. ||
Rule |
---|
...
Severity |
---|
...
Likelihood |
---|
...
Remediation Cost |
---|
...
Priority |
---|
...
Level |
---|
...
...
OBJ31-J |
...
medium | probable | low | P4 | L3 |
References
GCC Known Bugs C bugs, Aliasing issues while casting to incompatible types
Aliasing, pointer casts and gcc 3.3 Aliasing issue
References