When you define a struct in C, you might assume that the total size of the structure is simply the sum of the sizes of its individual members. However, this is rarely the case. Compilers automatically insert empty bytes—known as padding—between struct members.
CPUs read memory in word-sized chunks (e.g., 4 bytes on a 32-bit system, 8 bytes on a 64-bit system). To optimize CPU performance and minimize the number of memory read cycles, compilers align variables in memory based on their data type size. This is called Data Alignment.
sizeofLet's look at an example to see how padding affects the size of a struct.
#include <stdio.h>struct Unoptimized { char a; // 1 byte int b; // 4 bytes char c; // 1 byte };
int main() { // You might expect 1 + 4 + 1 = 6 bytes. // But the compiler adds padding! printf("Size of struct: %lu bytes\n", sizeof(struct Unoptimized)); return 0; }
What happens under the hood?
char a takes 1 byte.int b requires 4-byte alignment. So, the compiler inserts 3 bytes of padding after a.char c takes 1 byte.You can reduce the memory footprint of your structs by simply reordering the members from largest to smallest.
#include <stdio.h>struct Optimized { int b; // 4 bytes char a; // 1 byte char c; // 1 byte };
int main() { // 4 + 1 + 1 = 6. // Padded to the nearest multiple of 4: 8 bytes! printf("Size of optimized struct: %lu bytes\n", sizeof(struct Optimized)); return 0; }
By reordering, we saved 4 bytes of memory per struct instance! This becomes crucial when working with large arrays of structs in embedded systems.
What is the primary reason compilers add padding to structs in C?