Misaligned pointer
Detects when code accesses a misaligned pointer or creates a misaligned reference.
Overview
In Xcode 9 and later, you can use this check to detect reads from, or writes to, a misaligned pointer, or when you create a misaligned reference. A pointer misaligns if its address isn’t a multiple of its type’s alignment. Dereferencing a misaligned pointer has undefined behavior, and may result in a crash or degraded performance.
Alignment violations occur frequently in code that serializes or deserializes data. Avoid this issue by using a serialization format that preserves data alignment.
Misaligned integer pointer assignment in C
In the following example, the pointer variable must have 4-byte alignment, but has only 1-byte alignment:
int8_t *buffer = malloc(64);
int32_t *pointer = (int32_t *)(buffer + 1);
*pointer = 42; // Error: misaligned integer pointer assignmentSolution
Use an assignment function like memcpy, which can work with unaligned inputs.
int8_t *buffer = malloc(64);
int32_t value = 42;
memcpy(buffer + 1, &value, sizeof(int32_t)); // CorrectMisaligned structure pointer assignment in C
In the following example, the pointer variable must have 8-byte alignment, but has only 1-byte alignment:
struct A {
int32_t i32;
int64_t i64;
};
int8_t *buffer = malloc(32);
struct A *pointer = (struct A *)(buffer + 1);
pointer->i32 = 7; // Error: pointer is misalignedSolution
One solution is to pack the structure. In the following example, the packed A structure prevents the compiler from adding padding between members:
struct A { ... } __attribute__((packed));See Also
Undefined Behavior Sanitizer
Invalid Boolean valueOut-of-bounds array accessInvalid enumeration valueReaching of unreachable pointDynamic type violationInvalid float castDivision by zeroNonnull argument violationNonnull return value violationNonnull variable assignment violationNull reference creation and null pointer dereferenceInvalid object sizeInvalid shiftInteger overflowInvalid variable-length array