Course contentsShow
← C
Lesson 947 of 1,21913. Advanced CFree lesson

Structure padding and alignment issues

Structure padding and alignment issues

What you'll learn: How the C compiler rearranges internal memory layouts to keep your hardware happy, even if it wastes a few bytes.

The Tetris of Memory

Imagine you are packing a suitcase with books and thin bookmarks. The suitcase is divided into rigid 4-inch compartments. If you put a 1-inch bookmark next to a 4-inch book, the computer doesn't like to let the next book start at the 2-inch mark. It prefers to start every "big" item at the beginning of a fresh 4-inch slot because its "arms" (the CPU) are designed to grab memory in chunks of 4 or 8 bytes at a time.

In C, this is called alignment. To make data access fast, the compiler inserts invisible empty space—called padding—between members of a struct.

Seeing the Gaps

You might assume that a struct containing a char (1 byte) and an int (4 bytes) would take up 5 bytes. In reality, it usually takes up 8. The compiler places the char at the start, skips 3 bytes to reach a memory address divisible by 4, and then places the int.

#include <stdio.h>

struct Data {
    char a;     // 1 byte
    // 3 bytes of invisible padding inserted here!
    int b;      // 4 bytes
    char c;     // 1 byte
    // 3 bytes of trailing padding inserted here!
};

int main() {
    struct Data myData;
    printf("Size of struct: %zu bytes\n", sizeof(myData)); 
    // Usually prints 12, not 6!
    return 0;
}

Why Portability Matters

This behavior is "Implementation Defined." A compiler for a tiny 8-bit microwave might not use padding at all, while a 64-bit server might use massive gaps.

If you save a struct to a file on one computer and try to read it on another, the "invisible gaps" might be in different places. This breaks your data. To write portable code, you must be aware that sizeof(struct) is not just the sum of its parts. You can often minimize padding by ordering your variables from largest to smallest (putting all double and int members before char members).

Key takeaway

Compilers add invisible padding to structs to align data with hardware boundaries, meaning your structs are often larger than the sum of their individual members.