When we try to read misaligned memory, different things can happen depending on the CPU architecture and compiler settings. Let's look at three common scenarios:
On most modern x86/x64 processors, misaligned access works but is slower:
#include <chrono>
#include <iostream>
using namespace std::chrono;
struct Aligned {
int Value; // 4 bytes, naturally aligned
};
#pragma pack(1) // Force removal of padding
struct Misaligned {
char A; // 1 byte
int Value; // 4 bytes, misaligned!
};
#pragma pack()
int main() {
const int Iterations{10000000};
// Test aligned access
Aligned A;
auto Start = high_resolution_clock::now();
for (int i = 0; i < Iterations; ++i) {
A.Value = i; // Aligned access
volatile int Temp = A.Value;
}
auto AlignedTime =
high_resolution_clock::now() - Start;
// Test misaligned access
Misaligned M;
Start = high_resolution_clock::now();
for (int i = 0; i < Iterations; ++i) {
M.Value = i; // Misaligned access
volatile int Temp = M.Value;
}
auto MisalignedTime =
high_resolution_clock::now() - Start;
std::cout
<< "Aligned time: "
<< std::chrono::duration_cast<milliseconds>(
AlignedTime).count()
<< "ms\n"
<< "Misaligned time: "
<< std::chrono::duration_cast<milliseconds>(
MisalignedTime).count()
<< "ms\n";
}
On some architectures (like older ARM processors), misaligned access causes a hardware exception:
#include <iostream>
#pragma pack(1)
struct Dangerous {
char A;
int Value;
};
#pragma pack()
int main() {
Dangerous D;
D.Value = 42;// May trigger CPU exception!
}
Some platforms might silently corrupt data or behave unpredictably:
#include <iostream>
#pragma pack(1)
struct Risky {
char A;
int Value;
};
#pragma pack()
void ProcessValue(Risky& Data) {
// On some platforms, this might:
// - Read incorrect values
// - Corrupt nearby memory
// - Cause other undefined behavior
std::cout << Data.Value << "\n";
}
The takeaway is that while modern PCs often handle misaligned access gracefully (with a performance penalty), it's best to let the compiler handle alignment through padding to ensure our code works reliably across different platforms.
Answers to questions are automatically generated and may not have been reviewed.
Learn how memory alignment affects data serialization and how to handle it safely