CPU Architecture and Alignment
Do different CPU architectures handle alignment differently?
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.
Padding and Alignment
Learn how memory alignment affects data serialization and how to handle it safely