Skip to content

Struct Padding & Alignment

MarekBykowski edited this page May 26, 2026 · 1 revision
// Bad — 12 bytes (wasted padding)
struct foo { char a; int b; char c; };
// offsets: a=0, [3B pad], b=4, c=8, [3B pad] = 12B

// Good — 8 bytes (largest field first)
struct bar { int b; char a; char c; };
// offsets: b=0, a=4, c=5, [2B pad] = 8B
Tool What it does When to use
offsetof(T, f) field offset in bytes always safe
sizeof(struct T) total size with padding always
__attribute__((packed)) removes all padding protocols, not HW registers
_Alignas(N) forces alignment to N DMA buffers, cache lines

⚠️ packed = slower load (4× LDRB instead of LDR). On Cortex-M0 → HardFault on unaligned pointer access.

Clone this wiki locally