Why Computer Memory Needs Padding

Why do we need padding at all? Can't the computer just read the bytes it needs?

Modern CPUs are designed to read memory most efficiently when data is properly aligned. While it's technically possible to read individual bytes from any address, doing so can severely impact performance and, on some architectures, even cause crashes.

Let's understand why through an example. Imagine we have a 32-bit integer stored at memory address 1:

#include <iostream>

struct Unaligned {
  char A;// at offset 0
  int Value;// at offset 1 (unaligned!)
};

int main() {
  Unaligned Data;
  Data.A = 'X';
  Data.Value = 42;

  std::cout << "Size with alignment: "
    << sizeof(Unaligned) << " bytes\n";
}
Size with alignment: 8 bytes

When the CPU needs to read Value, it has to:

  1. Read bytes 1-4 (crossing a 4-byte boundary)
  2. Perform additional operations to combine these bytes
  3. Use more complex circuitry that handles unaligned access

Instead, with padding:

Offset: 0  1  2  3  4  5  6  7
        A  _  _  _  V  V  V  V
          ^Padding^ ^--Value--^

The CPU can now:

  1. Read all 4 bytes of Value in a single operation
  2. Use simpler circuitry optimized for aligned access
  3. Better utilize the cache line

This is why the compiler adds 3 bytes of padding after A - the small space "wasted" by padding is far outweighed by the performance benefits of aligned access.

Padding and Alignment

Learn how memory alignment affects data serialization and how to handle it safely

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Consequences of Misaligned Memory
What happens if we try to read memory that isn't properly aligned?
Memory Impact of Padding
Does padding waste a lot of memory in real programs?
Understanding Natural Alignment
How do I know what the natural alignment of a type should be?
CPU Architecture and Alignment
Do different CPU architectures handle alignment differently?
Alignment with Virtual Functions
How does alignment work with inheritance and virtual functions?
Understanding Union Alignment
How does alignment work with unions?
SIMD and Memory Alignment
How does alignment work with SIMD instructions?
Or Ask your Own Question
Purchase the course to ask your own questions