C++ › Memory Management

What is memory alignment and why does it matter?

Advanced

Answer

Alignment is the requirement that objects be placed at memory addresses that are multiples of their alignment (often their size), so the CPU can access them efficiently (or at all, on some architectures). alignof queries it and alignas sets it. Misalignment can cause performance penalties or hardware faults; it also affects struct padding and layout.
struct S { char c; int i; };  // padding inserted for i's alignment
static_assert(alignof(int) == 4);
Real-world example A struct is reordered and padded so each member meets its alignment, changing sizeof.

Common follow-ups: What is struct padding? | How do alignas/alignof work?