为什么这种越界访问没有段错误?
Why doesn't this out-of-bounds access segfault?
我正在为一个封装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;为什么突然有第三个我可以自由安全地访问?
因为这是未定义的行为,任何事情都可能发生,包括不会立即发生错误。我建议您使用容器,例如向量,它们是由好的调试编译器检查的边界。
相关文章:
- 为什么PyImport_ImportModule python 3.7.2 中出现段错误?
- 为什么在访问 vtkRenderWindow 的"交互器"变量时会发生段错误?
- 全局向量导致 C++ 程序结束时出现段错误
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 更改条件段错误
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 注册对对象工厂的调用会导致段错误
- pthread_create在构造函数段错误中
- Nanoflann发现邻居提出段错误
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 具有unique_ptr的 CRTP 会导致段错误
- 增强纤维work_stealing屏障会导致段错误
- 当我返回指向结构的指针向量时出现段错误
- C++为什么我的代码没有爆炸/段错误?
- Pthread段错误,使用指向main中变量的指针
- C++ 模板中的段错误
- 相当于Windows/MSVC上的段错误?
- 为什么我的 LLVM JIT 实现出现段错误?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?