Reordering members to reduce padding
What you'll learn: How to save memory by arranging structure members from largest to smallest to minimize the "empty space" added by the compiler.
The invisible gaps
When you define a struct, you might assume the computer stores the data tightly packed like sardines in a tin. However, CPUs prefer to access data at specific memory addresses (usually multiples of 4 or 8 bytes). To keep the CPU happy, the compiler inserts invisible "padding" bytes between members.
Think of it like packing a moving truck with a mix of large appliances and small shoe boxes. If you throw them in randomly, you end up with awkward gaps that you can’t fit anything into, wasting space.
A tale of two layouts
Consider a structure that holds a char (1 byte) and a double (8 bytes). Because a double usually requires 8-byte alignment, the compiler won't start it immediately after a single byte. It will insert 7 bytes of "dead air" so the double starts at a clean address.
Look at how the order changes the total size of the structure:
#include <stdio.h>
// Version 1: Poorly ordered (16 bytes)
struct Inefficient {
char a; // 1 byte
// 7 bytes of padding added here!
double b; // 8 bytes
char c; // 1 byte
// 7 bytes of padding added at the end
};
// Version 2: Optimized (16 bytes, but fits more data)
struct Efficient {
double b; // 8 bytes
char a; // 1 byte
char c; // 1 byte
// 6 bytes of padding at the end
};
// Version 3: The "Big-to-Small" rule (12 bytes)
struct Best {
double b; // 8 bytes
int d; // 4 bytes
char a; // 1 byte
};
In the Inefficient example, the char members act like "spacers" that force the compiler to add padding multiple times. By grouping the largest data types first, the smaller ones can often tuck into the remaining gaps at the end, significantly shrinking the structure's footprint.
The "Big-to-Small" rule
A reliable rule of thumb for C programming is to order your members by size, descending. Start with your double or long long types, move to int, then short, and put char at the very bottom.
While a few wasted bytes might not matter for a single variable, they add up quickly if you are creating an array of 100,000 structures. Proper ordering is a free optimization that improves cache performance and reduces your program's memory consumption.
Key takeaway
Arrange struct members from largest type to smallest to minimize memory gaps created by compiler padding.