Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么';这不是越界进入故障吗?_C++_Arrays_Segmentation Fault - Fatal编程技术网

C++ 为什么';这不是越界进入故障吗?

C++ 为什么';这不是越界进入故障吗?,c++,arrays,segmentation-fault,C++,Arrays,Segmentation Fault,我在测试一个类的一些代码,这个类封装了一个二维数组structs 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

我在测试一个类的一些代码,这个类封装了一个二维数组
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;

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

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

请提供完整的测试用例来重现此行为!它不是必需的,自动边界检查将为您在任何情况下都不需要的东西付费。这就是为什么幻数是一件坏事的一个例子。您应该在代码中的某个地方定义一个常量,而不是3,因为越界访问是未定义的行为,而未定义的行为是未定义的。
0x7ffdadface08
0
0
0
-
0x7ffdadface14
0
0
0
-
0x7ffdadface20
0
0
0