---
title: Misaligned pointer
framework: xcode
role: article
role_heading: Article
path: xcode/misaligned-pointer
---

# Misaligned pointer

Detects when code accesses a misaligned pointer or creates a misaligned reference.

## Overview

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 assignment Solution 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)); // Correct note: The compiler can often safely optimize calls to memcpy, even for unaligned arguments. Misaligned 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 misaligned Solution 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)); important: Packing a structure may adversely impact performance.

## See Also

### Undefined Behavior Sanitizer

- [Invalid Boolean value](xcode/invalid-boolean.md)
- [Out-of-bounds array access](xcode/out-of-bounds-array-access.md)
- [Invalid enumeration value](xcode/invalid-enumeration-value.md)
- [Reaching of unreachable point](xcode/reaching-of-unreachable-point.md)
- [Dynamic type violation](xcode/dynamic-type-violation.md)
- [Invalid float cast](xcode/invalid-float-cast.md)
- [Division by zero](xcode/division-by-zero.md)
- [Nonnull argument violation](xcode/nonnull-argument-violation.md)
- [Nonnull return value violation](xcode/nonnull-return-value-violation.md)
- [Nonnull variable assignment violation](xcode/nonnull-variable-assignment-violation.md)
- [Null reference creation and null pointer dereference](xcode/null-reference-creation-and-null-pointer-dereference.md)
- [Invalid object size](xcode/invalid-object-size.md)
- [Invalid shift](xcode/invalid-shift.md)
- [Integer overflow](xcode/integer-overflow.md)
- [Invalid variable-length array](xcode/invalid-variable-length-array.md)
