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.
Section 6.3.2.3, para. 7, of the C standard Standard [ISO/IEC 9899:2011] , states:
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 25 of in Annex J of the C Standard.)
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 assertion in the following code example will fail on some conforming implementations, even though no pointers are dereferenced:
...
Noncompliant Code Example
The C standard allows Standard allows a pointer to be cast into and out of void *
. As a result, it is possible to silently convert from one pointer type to another without the compiler diagnosing the problem by storing or casting a pointer to void *
and then storing or casting it to the final type. In this noncompliant code example, the type checking system is circumvented due to the caveats of void
pointers.
...
This example compiles without warning. However, v_pointer
can be aligned on a one1-byte boundary.
Compliant Solution
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
| 94 S | Fully implemented | |||||||
GCC |
| Can detect some violations of this rule when the | |||||||
EDG | |||||||||
Compass/ROSE | Can detect violations of this rule. However, it does not flag explicit casts to | ||||||||
| castexpr | Fully implemented. | |||||||
PRQA QA-C |
| 3305 | Fully implemented. |
Noncompliant Code Example
For objects declared on the stack, the C standard [ISO/IEC 9899:2011] provides alignas
to declare an object to have a stricter alignment. It can be used to resolve the following noncompliant code example.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
ISO/IEC TR 17961 | (Draft) Converting pointer values to more strictly aligned pointer types [alignconv] |
ISO/IEC TR 24772 |
...
Pointer casting and pointer type changes |
...
[HFC] | |
MISRA-C | Rules 11.2 and 11.3 |
Bibliography
...
[Bryant 2003] | |
---|---|
[ISO/IEC 9899:2011] | Section 6.2.5, "Types" |
[Walfridsson 2003] | Aliasing, Pointer Casts and GCC 3.3 |