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 C99C11, Section 6.3.2.3, para. 7, 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 25 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 assertion in the following code is not guaranteed to work conforming C99 example will fail on some conforming implementations, even though no pointers are dereferenced:
Code Block |
---|
char c = 'x'; int *ip = (int *)&c; /* this can lose information */ char *cp = (char *)ip; assert(cp == &c); /* will fail on some conforming implementations */ |
On some implementations, cp
will not match &c
. As a result, if a pointer to one object type is converted to a pointer to a different object type, the second object type must not require stricter alignment than the first.
Noncompliant Code Example
C99 and C90 allow The C 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.
...
Tool | Version | Checker | Description | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Section |
| section94 S | 540 S | ||||||||||||||
Section | Fully | Implementedimplemented | |||||||||||||||
Section | |||||||||||||||||
GCC |
| section | Can detect some violations of this rule when the | ||||||||||||||
Section | |||||||||||||||||
EDG | |||||||||||||||||
Section | Compass/ROSE | ||||||||||||||||
Section | Can detect violations of this rule. However, it does not flag explicit casts to | ||||||||||||||||
Section |
| ||||||||||||||||
Section | castexpr | sectionFully | Implementedimplemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: EXP36-CPP. Do not convert pointers into more strictly aligned pointer types
ISO/IEC 9899:19992011 Section 6.2.5, "Types"
ISO/IEC TR 17961 (Draft) Converting pointer values to more strictly aligned pointer types [alignconv]
ISO/IEC TR 24772 "HFC Pointer casting and pointer type changes"
...