为什么这种越界访问不会出现段错误?
Why doesn't this out-of-bounds access segfault?
我正在测试 class 的一些代码,它包装了 struct
的二维数组。
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
为什么这段代码不会出现 "access out of bounds" 错误之类的段错误?我只在数组中创建了 2 个结构;为什么突然有第三个我可以自由安全访问的?
因为它是未定义的行为,任何事情都可能发生,包括不会立即出现错误。我建议您使用诸如 vector 之类的容器,这些容器由良好的调试编译器进行边界检查。
我正在测试 class 的一些代码,它包装了 struct
的二维数组。
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
为什么这段代码不会出现 "access out of bounds" 错误之类的段错误?我只在数组中创建了 2 个结构;为什么突然有第三个我可以自由安全访问的?
因为它是未定义的行为,任何事情都可能发生,包括不会立即出现错误。我建议您使用诸如 vector 之类的容器,这些容器由良好的调试编译器进行边界检查。