【发布时间】:2019-07-03 18:52:42
【问题描述】:
以前有一些关于内存对齐的很好的答案,但我觉得没有完全回答一些问题。
例如:
What is data alignment? Why and when should I be worried when typecasting pointers in C?
What is aligned memory allocation?
我有一个示例程序:
#include <iostream>
#include <vector>
#include <cstring>
int32_t cast_1(int offset) {
std::vector<char> x = {1,2,3,4,5};
return reinterpret_cast<int32_t*>(x.data()+offset)[0];
}
int32_t cast_2(int offset) {
std::vector<char> x = {1,2,3,4,5};
int32_t y;
std::memcpy(reinterpret_cast<char*>(&y), x.data() + offset, 4);
return y;
}
int main() {
std::cout << cast_1(1) << std::endl;
std::cout << cast_2(1) << std::endl;
return 0;
}
cast_1 函数输出 ubsan 对齐错误(如预期),但 cast_2 没有。但是,cast_2 对我来说可读性要差得多(需要 3 行)。 cast_1 的意图看起来非常清楚,即使它是 UB。
问题:
1) 为什么是cast_1 UB,意图非常明确?我了解对齐可能存在性能问题。
2) cast_2 是修复 cast_1 的 UB 的正确方法吗?
【问题讨论】:
标签: c++ memory-alignment