How is a C union laid out in memory, and how does that differ from a struct?
All members of a union share the same memory starting at offset 0 — they overlap, so the union is only as big as its largest member, unlike a struct whose members sit side by side.
* A struct stores all members side by side (sum of sizes); a union overlaps them at offset 0, so its size is just its largest member. *
A struct places its members one after another (with padding), so its size is roughly the sum of its fields. A union does the opposite: every member begins at offset 0 and they all occupy the same bytes. Writing one member therefore overwrites the others — a union holds only one of its members meaningfully at a time.
union u {
char c; // all three live at
int i; // the same address
double d; // (offset 0)
};
Size and alignment rules:
- Size = the size of the largest member (not the sum), since they overlap.
- Alignment = the strictest alignment requirement among the members — same rule as a struct.
- Address of every member = the start of the union (offset 0).
Why use one? To reinterpret the same bytes as different types (e.g. inspect the raw bytes of a float), or to save memory when you know only one field is needed at a time.
Reverse-engineering relevance: a union has no per-field offsets to spot, so in disassembly the same memory location being read as different sizes/types is the tell-tale sign of a union.
Go deeper:
Union type (Wikipedia) — union members overlapping at the same address vs struct layout.