Course contentsShow
← C
Lesson 573 of 1,2198. Memory ManagementFree lesson

Struct padding for alignment

Struct padding for alignment

What you'll learn: How the CPU’s need for efficiency forces the compiler to insert "invisible" empty space between members of a struct.

The CPU is a picky eater

Imagine you are eating a sandwich cut into four neat squares. You can easily pick up one square at a time. Now imagine the sandwich is thrown into a blender and poured onto the plate. You could still eat it, but it would be much slower and messier.

CPUs are similarly picky. They don't read memory one byte at a time; they read in "chunks" (usually 4 or 8 bytes). To keep performance high, the CPU wants specific data types to start at specific addresses. For example, a 4-byte int usually needs to start at an address that is a multiple of 4. This requirement is called alignment.

Mind the gap

When you define a struct, you might assume the members are packed tightly together. However, if the data types don't line up perfectly with the CPU’s preferred boundaries, the compiler inserts "padding"—useless, invisible bytes—to push the next member to a valid starting line.

Take a look at this example:

#include <stdio.h>

struct Resource {
    char status;    // 1 byte
    // 3 bytes of invisible padding inserted here!
    int quantity;   // 4 bytes
};

int main() {
    struct Resource r;
    printf("Size of char: %zu byte\n", sizeof(char));
    printf("Size of int: %zu bytes\n", sizeof(int));
    printf("Actual size of struct: %zu bytes\n", sizeof(r));
    return 0;
}

Even though a char is 1 byte and an int is 4 bytes, sizeof(Resource) will likely return 8 bytes, not 5. The compiler sees that the int would start at an "odd" address (index 1), so it adds 3 bytes of padding after the char so the int can start at index 4.

Why does this matter?

Padding ensures the CPU can grab the int in a single memory cycle. If the int were split across two different chunks of memory, the CPU would have to perform two reads and some extra math just to get one number, slowing down your program.

While padding helps speed, it can waste memory. If you have an array of a million structs, those 3 bytes of padding suddenly become 3 megabytes of wasted space!

Key takeaway

Struct padding is invisible "buffer space" added by the compiler to ensure data aligns with the CPU's memory boundaries for maximum speed.