C Struct Alignment and Padding

1. What is C Struct Alignment and Padding?
Alignment ensures that data members of a struct store at memory addresses suitable for their type.
Many CPUs require certain types (like
intordouble) to be stored at memory addresses that are multiples of their size.Accessing misaligned data can be slower or even cause hardware exceptions.
2. What is Padding?
Padding is extra unused memory added by the compiler to satisfy alignment requirements.
It ensures that each member is properly align.
As a result, the size of a struct may be larger than the sum of its members.
3. Example: Struct Alignment and Padding
Output (typical on 32-bit/64-bit system):
Explanation:
| Member | Size | Alignment | Memory Offset |
|---|---|---|---|
c | 1 | 1 | 0 |
| padding | 3 | 1–3 | |
i | 4 | 4 | 4–7 |
d | 1 | 1 | 8 |
| padding | 3 | 9–11 |
Total size = 12 bytes (not 6 bytes).
Padding ensures that
int istarts at address divisible by 4.
4. How to Reduce Padding
Reorder members by decreasing size:
Now, size is usually 8 bytes instead of 12.
5. Struct Alignment Rules (General)
Each member store at address multiple of its size (alignment requirement).
Compiler may add padding between members.
Total size of struct is often rounded up to the largest alignment of its members.
Arrays of structs maintain same alignment for each element.
6. Using #pragma pack (Optional)
You can control padding using compiler-specific directives:
Output:
Warning: Packing can cause misaligned accesses, which may slow down or crash some CPUs.
7. Key Points About C Struct Alignment and Padding
Alignment ensures CPU-friendly memory access.
Padding adds extra bytes between members.
Size of struct may be larger than sum of members.
Reordering members can reduce padding.
Use
#pragma packcarefully to control alignment.Understanding alignment is important for embedded systems, memory-efficient programs, and binary file formats.
