数组溢出(为什么会这样?) [英] Array overflow (why does this work?)
问题描述
好的,所以我正在教我的女朋友一些 C++,她写了一个我认为行不通的程序,但它确实成功了.它再访问数组中的一个元素(例如,访问数组 [5] 以获得大小为 5 的数组).这是缓冲区溢出的一个实例吗?我的想法是它在数组之后直接写入/访问内存,这是正确的吗?基本上我的问题是..为什么会这样?
Okay, so I was teaching my girlfriend some c++, and she wrote a program that I thought wouldn't work, but it did. It accesses one more element in the array then there is (for instance, accessing array[5] for an array of size 5). Is this an instance of a buffer overflow? My thoughts on it are that it's writing to/accessing the memory directly after the array, is this correct? Basically my question here is..why does this work?
#include <iostream>
using namespace std;
int main()
{
int size;
cout << "Please enter a size for the array." << endl;
cin >> size;
cout << endl;
cout << "There are " << size << " elements in this array." << endl;
cout << endl;
cout << endl;
cout << endl;
int array[size];
for (int counter = 1; counter <= size; counter++)
{
cout << "Please enter a value for element " << counter << "." << endl;
cin >> array[counter];
}
cout << endl;
cout << endl;
for (int counter = 1; counter <= size; counter++)
{
cout << "Element " << counter << " is " << array[counter] << "." << endl;
cout << endl;
}
cout << "*bing! :)" << endl;
cout << endl;
return 0;
}
推荐答案
这是未定义的行为.UB 有多种口味.以下是一些:
It's undefined behavior. UB comes in many flavors. Here are a few:
1) 它会踢你的狗.
2) 它将重新格式化您的硬盘.
2) It will reformat your hard drive.
3) 它可以毫无问题地工作.
3) It will work without a problem.
在您的情况下,使用您的编译器和您的平台以及在这一天,您会看到 (3).但是在其他地方尝试它,您可能会得到 (1)、(2) 或其他完全的结果(很可能是访问冲突).
In your case, with your compiler and on your platform and on this particular day, you are seeing (3). But try it elsewhere, and you might get (1), (2), or something else completely (most likely an access violation).
这篇关于数组溢出(为什么会这样?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!