[英]What's the difference in following code, when I use parentheses I get expected result but random number if I don't use the parentheses
[英]Why don't I get an error when I run the following code
我正在运行以下代码,其中我声明了一个动态 2D 数组,然后继续在高于实际分配给动态数组的列数的列索引处分配值。 但是,当我这样做时,代码运行得很好,我没有收到错误,我相信我应该得到。
void main(){
unsigned char **bitarray = NULL;
bitarray = new unsigned char*[96];
for (int j = 0; j < 96; j++)
{
bitarray[j] = new unsigned char[56];
if (bitarray[j] == NULL)
{
cout << "Memory could not be allocated for 2D Array.";
return;// return if memory not allocated
}
}
bitarray[0][64] = '1';
bitarray[10][64] = '1';
cout << bitarray[0][64] << " " << bitarray[10][64];
getch();
return;
}
我得到的输出链接在这里(这些值实际上是准确分配的,但不知道为什么)。
在 C++ 中,访问缓冲区超出其边界会调用未定义的行为(不是您预期的捕获错误)。
C++ 规范将术语未定义行为定义为:
本国际标准未规定要求的行为。
在您的代码中,两者
bitarray[0][64] = '1';
bitarray[10][64] = '1';
正在访问内存越界,。 即,那些内存位置是“无效的”。 访问无效内存会调用未定义的行为。
访问冲突错误或分段错误是 UB 的众多可能结果之一。 什么都不能保证。
在使用硬件内存分段来提供虚拟内存的系统上,当硬件检测到尝试引用不存在的段或引用段边界之外的位置时,会发生段错误,......
所以,也许,只是也许, bitarray[0][64]
的内存区域在分配的页面(段)内,在这个非常特殊的情况下,程序可以访问(但无论如何都是无效的)。 这并不意味着它会一直如此。
也就是说, void main()
不是main()
函数的正确签名。 main()
的推荐( C++11
,§3.6.1)签名是int main(void)
。
C++11 引入了std::array并且方法at()
提供了越界检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.