capypad
0 day streak
c / expert
Snippet

Memory Alignment and Struct Padding

CPUs often access memory in multi-byte chunks (word size). To optimize access, compilers align structure members to specific boundaries. This results in 'padding'—wasted space between members. Expert developers reorder structure members from largest alignment requirement to smallest to minimize memory footprint and improve cache efficiency.

snippet.c
c
1
2
3
4
5
6
struct Optimized {
double a; // 8 bytes
int b; // 4 bytes
char c; // 1 byte
char _pad[3]; // 3 bytes implicit padding
}; // Total 16 bytes
Breakdown
1
double a;
Requires 8-byte alignment on most 64-bit systems.
2
char _pad[3];
Implicit bytes added to ensure the total struct size is a multiple of the largest alignment.