How are C structures laid out in memory, and what determines their total size?
Members are stored in declaration order, each padded to satisfy its alignment, and the whole struct is padded up to a multiple of its largest member's alignment.
* Members in declaration order, each aligned; total size rounded up to a multiple of the largest alignment. *
A struct is a contiguous region holding its members in order, non-overlapping, and each properly aligned. The compiler inserts "holes" (padding) so every member starts at an address that's a multiple of its own alignment requirement.
struct rec {
int a[3]; // offset 0, size 12
int i; // offset 12, size 4
struct rec *n; // offset 16, size 8 (pointer needs 8-byte alignment)
}; // total size: 24 bytes
Layout:
| a[0..2] | i | n |
0 12 16 24
Rules:
- Each member is aligned to its own type's requirement (so padding may appear between members).
- The struct's alignment = the max alignment of any member.
- The struct's size is rounded up to a multiple of that alignment, so arrays of the struct stay aligned (this is why a trailing pad may be added).
- Address of member
k= base + (sum of sizes and paddings of members0..k-1).
Practical consequence: member ordering changes the size. Putting large/strictly-aligned members first and small ones last minimizes wasted padding bytes.
Go deeper:
Data structure alignment (Wikipedia) — alignment, padding and how they set the size.
struct in C (Wikipedia) — the C struct itself.