Do not convert convert a pointer value to a pointer type that is more strictly aligned than the referenced type. Different 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.
The C Standard, 6.3.2.3, paragraph 7 [ISO/IEC 9899:2011], states:
...
In this noncompliant example, the char
pointer pointer &c
is is converted to the more strictly aligned int
pointer pointer ip
. On some implementations, cp
will 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.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <assert.h> void func(void) { char c = 'x'; int *ip = (int *)&c; /* This can lose information */ char *cp = (char *)ip; /* Will fail on some conforming implementations */ assert(cp == &c); } |
...
In this compliant solution, the char
value value is stored into an object of type int
so so that the pointer's value will be properly aligned:
...
Related Guidelines
CERT C++ Secure Coding Standard | EXP36EXP56-CPP. Do not convert cast pointers into more strictly aligned pointer types |
ISO/IEC TR 24772:2013 | Pointer Casting and Pointer Type Changes [HFC] |
ISO/IEC TS 17961 | Converting pointer values to more strictly aligned pointer types [alignconv] |
MISRA C:2012 | Rule 11.1 (required) Rule 11.2 (required) Rule 11.5 (advisory) Rule 11.7 (required) |
...