...
In this noncompliant example, the char pointer &c is converted to the more strictly aligned int pointer ip. 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.
...
This compliant solution uses alignas to align the character c to the alignment of an integer. As a result, the two pointers point to reference equally aligned pointer types:
...
Another solution is to ensure that loop_ptr points to an object returned by malloc() because this object is guaranteed to be suitably aligned properly for any needthe storage of any type of object. However, this subtlety is easily missed when the program is modified in the future. It is easier and safer to let the type system document the alignment needs.
...
Many architectures require that pointers are correctly aligned when accessing objects larger than a byte. There areIt is common is system code, however, many places in system code where you receive that unaligned data (for example, the network stacks) that needs to must be copied to a properly aligned memory location, such as in this noncompliant code example:
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <string.h>
struct foo_header {
int len;
/* ... */
};
void func(char *data, size_t offset) {
struct foo_header *tmp;
struct foo_header header;
tmp = data + offset;
memcpy(&header, tmp, sizeof(header));
/* ... */
} |
Unfortunately, the behavior is undefined when you assign assigning an unaligned value to a pointer that points to references a type that needs to be aligned is undefined behavior. An implementation may notice, for example, that tmp and header must be aligned , so it could and use an inlined inline memcpy() that uses instructions that assume aligned data.
...
EXP36-EX1: Some platforms, notably x86, have relaxed requirements with regard to pointer alignment. Using a pointer that is not properly aligned is correctly handled by the platform, although the platform may impose there might be a performance penalty. On such a platform, improper pointer alignment is permitted, as it is an efficiency problem but not a security problem.
...