Padding and Alignment

Why Computer Memory Needs Padding

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Padding and Alignment

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Padding and Alignment

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

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 75 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved