Padding and Alignment

CPU Architecture and Alignment

Do different CPU architectures handle alignment differently?

Abstract art representing computer programming

Yes, different CPU architectures have varying alignment requirements and behaviors. Let's look at some key differences:

x86/x64 (Intel/AMD)

Modern x86 processors are relatively forgiving:

#include <iostream>

#pragma pack(1)
struct Misaligned {
  char A;
  int B;
};
#pragma pack()

int main() {
  Misaligned Data{'X', 42};
  // On x86/x64: Works, but slower
  std::cout << Data.B << "\n";
}

ARM

ARM processors are stricter about alignment:

#include <iostream>

#pragma pack(1)
struct Misaligned {
  char A;
  int B;
} Data{'X', 42};
#pragma pack()

int main() {
  // On older ARM: May cause hardware exception!
  // On newer ARM: May trigger alignment fault handler
  std::cout << Data.B << "\n";
}

RISC Architectures

RISC processors often have strict alignment rules:

#include <iostream>

struct AlignmentMatters {
  // On RISC:
  short Value;// Must be 2-byte aligned
  int Data;// Must be 4-byte aligned
  double Price;// Must be 8-byte aligned
};

int main() {
  std::cout << "Size on RISC: "
    << sizeof(AlignmentMatters) << "\n";
}

To write portable code that works across architectures:

  • Let the compiler handle alignment
  • Don't use #pragma pack unless absolutely necessary
  • Test on different platforms when possible
  • Use standard C++ serialization when sharing data
  • Be extra careful with embedded systems

The key takeaway is that while modern PC architectures handle misalignment gracefully (with performance penalties), other platforms may be less forgiving. Writing properly aligned code ensures maximum portability.

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