Different alignments are possible for different types of objects. If the type-checking system is overridden by an explicit cast or the pointer is converted to a void pointer (void *
) and then to a different type, the alignment of an object may be changed.
According to C99, Section 6.3.2.3 p7 (see also undefined behavior 22 of Annex J):, p7
A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined.
(See also undefined behavior 22 of Annex J.)
If the misaligned pointer is dereferenced, the program may terminate abnormally. The cast alone may cause a loss of information, even if the value is not dereferenced. For example, the following code is not guaranteed to work conforming C99 implementations, even though no pointers are dereferenced:
...
Many architectures requires that pointers are correctly aligned when accessing objects bigger than a byte. There are, however, many places in system code where you receive unaligned data (e.g., the network stacks) that needs to be copied to a properly aligned memory location such as in this noncompliant code example.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP36-C | low | probable | medium | P4 | L3 |
Automated Detection
The LDRA tool suite V 7.6.0 can detect violations of this rule.
...
Tool | Version | Checker | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
| ||||||||||
|
|
|
| ||||||||||
|
...
|
...
|
|
| |||||
|
|
|
|
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
Related Guidelines
This rule appears in the C++ Secure Coding Standard as : EXP36-CPP. Do not convert pointers into more strictly aligned pointer types.
Bibliography
Wiki Markup |
---|
[Walfridsson 032003] Krister Walfridsson. [Aliasing, pointer casts and gcc 3.3|http://mail-index.netbsd.org/tech-kern/2003/08/11/0001.html]. August, 2003. \[[Bryant 032003|AA. Bibliography#Bryant 03]\] \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.2.5, "Types" \[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] "HFC Pointer casting and pointer type changes" \[[MISRA 042004|AA. Bibliography#MISRA 04]\] Rules 11.2 and 11.3 |
...