⚙️ C++ Advanced

What is memory alignment and padding in C++?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

Memory alignment is the requirement that data of a given type be stored at memory addresses that are multiples of the type's alignment requirement. Modern CPUs access aligned data more efficiently — misaligned access may require multiple memory operations or cause hardware faults on some architectures. Alignment of types: alignof(char) == 1 // 1-byte aligned alignof(int) == 4 // 4-byte aligned alignof(double) == 8 // 8-byte aligned. Struct padding: the compiler inserts padding bytes to ensure each member is properly aligned: struct Wasteful { char a; // 1 byte // 3 bytes padding (int needs 4-byte alignment) int b; // 4 bytes char c; // 1 byte // 3 bytes padding (struct end aligned to largest member) }; // sizeof(Wasteful) = 12 struct Efficient { int b; // 4 bytes char a; // 1 byte char c; // 1 byte // 2 bytes padding }; // sizeof(Efficient) = 8. Rule: order struct members from largest to smallest alignment to minimize padding. Checking: static_assert(sizeof(Wasteful) == 12); static_assert(offsetof(Wasteful, b) == 4); // 3 bytes padding. #pragma pack / __attribute__((packed)): reduce or eliminate padding — risky (unaligned access UB, slower, breaks SIMD): #pragma pack(1) struct Packed { char a; int b; }; // sizeof = 5 #pragma pack(). alignas (C++11): override default alignment: alignas(64) char cacheLinePadding[64]; // Force 64-byte cache line alignment alignas(16) float vec[4]; // SIMD alignment. std::aligned_storage, std::aligned_alloc: allocation with specific alignment requirements. Cache line awareness: false sharing — two threads modifying variables in the same 64-byte cache line causes performance issues. Pad to separate cache lines: struct PaddedCounter { alignas(64) std::atomic<int> count; char padding[60]; // Ensure next counter is on separate line };

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.