Topics / Pointers & Memory / Q14
What is alignment and what happens on an unaligned access?
Short answer: An object is aligned when its address is a multiple of its alignment requirement, which for basic types is usually their size (a uint32_t at an address divisible by 4). The compiler aligns variables and adds struct padding automatically. Unaligned accesses usually come from casting byte pointers; depending on the CPU they are slower, need extra instructions, or fault.
Behaviour by core
| Core | Unaligned LDR/STR (word/halfword) |
Notes |
|---|---|---|
| Cortex-M0/M0+/M23 (Armv6-M/v8-M baseline) | HardFault | no unaligned support at all |
| Cortex-M3/M4/M7/M33 | supported in hardware, slower (split into two accesses) | LDRD/STRD, LDM/STM still fault; can be made to trap with CCR.UNALIGN_TRP |
| Cortex-A (ARMv7-A/ARMv8-A) | supported for normal memory | faults on Device memory (peripherals) and for exclusive/atomic instructions |
| x86 | supported, small penalty | atomics across cache lines are very slow (split locks) |
The classic bug
void parse(const uint8_t *buf) /* buf from a UART or network packet */
{
uint32_t len = *(const uint32_t *)(buf + 1); /* unaligned if buf+1 is not a multiple of 4,
and also a strict-aliasing violation */
}
Correct, portable approaches
uint32_t len;
memcpy(&len, buf + 1, sizeof len); /* compiler emits the best sequence for the target */
uint32_t len_le = (uint32_t)buf[1] | (uint32_t)buf[2] << 8 |
(uint32_t)buf[3] << 16 | (uint32_t)buf[4] << 24; /* also fixes byte order */
Controlling alignment
_Alignas(32) uint8_t dma_buf[512];(C11) or__attribute__((aligned(32)))for cache-line-aligned DMA buffers.alignof(T)(C11_Alignof) gives a type's requirement.aligned_alloc(align, size)for aligned heap memory.- Packed structs remove padding but may create unaligned members (see the C topic).
Why alignment matters beyond correctness: aligned data never spans two cache lines or two bus transactions; DMA controllers often require aligned buffers; and atomic operations generally require natural alignment.