【发布时间】:2018-01-18 21:43:42
【问题描述】:
我的目标是分配一块内存,然后将其划分为不同类型的较小数组。我对我在这里写的代码有几个问题:
#include <iostream>
#include <cstdint>
#include <cstdlib>
int main() {
constexpr std::size_t array_count = 5;
constexpr std::size_t elements_size = sizeof(std::uint32_t) + sizeof(std::uint16_t);
void* const pv = std::calloc(array_count, elements_size);
//Partition the memory. p32 array starts at pv, p16 array starts after the 20 byte buffer for the p32 array.
std::uint32_t* const p32 = (std::uint32_t *) pv;
std::uint16_t* const p16 = (std::uint16_t *)((char *) pv + sizeof(std::uint32_t) * array_count);
//Initialize values.
for(std::size_t i = 0; i < array_count; ++i) {
p32[i] = i;
p16[i] = i * 2;
}
//Read them back.
for(std::size_t i = 0; i < array_count; ++i) {
std::cout << p32[i] << std::endl;
std::cout << p16[i] << std::endl;
std::cout << std::endl;
}
std::free(pv);
}
- 此代码是否违反 c++ 的严格别名规则?从 malloc 或 calloc 调用中转换指针时,我无法找到有关别名的资源。 p32 和 p16 指针不应重叠。
- 如果我反转两个数组的定位,其中 p16 从 pv 开始,并且 p32 与 pv 有 10 字节偏移,这可能会导致段错误,因为 uint32_t 与 4 字节边界对齐 pv + 10 可能在 2 字节上边界,对吧?
- 此程序是否不安全,或引入了我通常缺少的任何未定义行为?我在本地机器上得到了预期的输出,但这并不意味着我的代码是正确的。
【问题讨论】:
标签: c++ pointers memory-management c++14