为什么这种越界访问没有段错误?

Why doesn't this out-of-bounds access segfault?

本文关键字:错误 段错误 越界 访问 为什么      更新时间:2023-10-16

我正在为一个封装struct s的二维数组的类测试一些代码。

WrapperClass x;
SomeStruct try1 = x.at(0, 0);
SomeStruct try2 = x.at('a', 1);
SomeStruct array[] = {try1, try2};
// There were originally 3 of these test variables above, but I forgot to
// change the loop upper bound when I deleted one
for (int i = 0; i < 3; i++) {
    // I added this line after noticing the non-error
    std::cout << &array[i] << 'n';
    std::cout << array[i].property1 << 'n';
    std::cout << array[i].property2 << 'n';
    std::cout << array[i].property3 << 'n';
    std::cout << "-n";
}
return 0;

该输出:

0x7ffdadface08
0
0
0
-
0x7ffdadface14
0
0
0
-
0x7ffdadface20
0
0
0

为什么这个代码没有出现"访问越界"错误或其他什么错误?我只在数组中创建了2个structs;为什么突然有第三个我可以自由安全地访问?

因为这是未定义的行为,任何事情都可能发生,包括不会立即发生错误。我建议您使用容器,例如向量,它们是由好的调试编译器检查的边界。