SNIPPET 6

Structure Packing

Reorder structure members to mathematically eliminate hidden padding and minimize total memory usage.

Silicon Logic

Compilers align variables in memory based on their size to optimize CPU fetch cycles. For instance, a 4-byte uint32_t must cleanly begin at an address divisible by 4.

If a 1-byte uint8_t precedes a uint32_t, the compiler will secretly insert 3 invisible "padding" bytes to bump the 4-byte variable onto a valid boundary.

The Rule: Reordering struct members from largest to smallest systematically eliminates internal padding holes, often shrinking the struct’s footprint heavily.

struct_optimization.c
#include <stdint.h>
// Bad alignment (causes internal padding holes)
struct BadPack {
uint8_t a; // 1 byte
uint32_t b; // 4 bytes
uint16_t c; // 2 bytes
};
// Good alignment (ordered largest to smallest)
struct GoodPack {
uint32_t b; // 4 bytes
uint16_t c; // 2 bytes
uint8_t a; // 1 byte
};
int main() {
int bad_bytes = sizeof(struct BadPack);
int good_bytes = sizeof(struct GoodPack);
return 0;
}