c language · advanced
C: Struct Padding & Alignment
C compilers insert padding bytes between struct members so each meets its alignment requirement (an int typically must start at an address divisible by 4), because misaligned access is slow or faulty on many CPUs. Consequently a struct's size exceeds the naive sum of its members — struct { char a; int b; char c; } is 12 bytes, not 6, because 3 pad bytes follow a to align b, and the whole struct's size is rounded up to a multiple of its largest member's alignment so arrays stay aligned. Because padding depends on declaration order, reordering members from largest to smallest alignment minimizes waste: { int; char; char; } is 8 bytes versus 12 for { char; int; char; }; offsetof(type, member) reveals where members truly sit (b at offset 4, not 1), and alignof/alignas query and adjust alignment. #pragma pack(1) or __attribute__((packed)) removes padding to obtain an exact byte layout for wire protocols and file formats, but it can leave members misaligned, and taking and dereferencing a pointer to a misaligned member is undefined behavior on strict-alignment platforms and slow elsewhere — so prefer serializing field by field with memcpy over reinterpreting a packed struct.
C struct padding: the compiler inserts filler so each member meets its alignment, so sizeof exceeds the member sum and member order changes the size (order big->small to shrink); #pragma pack removes padding for wire layouts but can misalign members (deref = UB on strict CPUs).
The code
struct Bad { char a; int b; char c;}; // sizeof == 12 (padding!)struct Good { int b; char a; char c;}; // sizeof == 8
// Bad layout: a | pad pad pad | b b b b | c | pad pad pad// 1 3 4 1 3 = 12
offsetof(struct Bad, b); // 4, not 1 — b is aligned to 4#pragma pack(push, 1) struct Packed{char a; int b; }; // sizeof 5What this lesson walks through
- 01Why padding exists
- 02Member order changes the size
- 03Gotcha — never memcmp two structs
- 04#pragma pack — smaller but unaligned
int must sit at a 4-byte-aligned offset. struct Bad orders char, int, char, so the compiler inserts 3 pad bytes after each char — sizeof balloons to 12.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of C: Struct Padding & Alignment and 100+ animated C++ interview lessons.