数组溢出(为什么这项工作?) [英] Array overflow (why does this work?)

查看:78
本文介绍了数组溢出(为什么这项工作?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我教我的女朋友了一些C ++和她写的,我认为是行不通的方案,但它确实。它访问阵列中一个多元件则存在(例如,访问阵列[5]为大小为5的阵列)。这是一个缓冲区溢出的实例?我在上面的想法是,它的写入/阵列后,直接访问内存,这是正确的?基本上在这里我的问题is..why做这项工作?

 的#include<&iostream的GT;使用命名空间std;诠释的main()
{
INT大小;COUT<< 请为阵列输入大小。 << ENDL;
CIN>>尺寸;
COUT<< ENDL;COUT<< 有<<大小和LT;< 元素此数组中。 << ENDL;
COUT<< ENDL;
COUT<< ENDL;
COUT<< ENDL;int数组【规格】;对于(INT计数器= 1;计数器< =大小;反++){
    COUT<< 请输入元素的值<其中p计数器<< 。 << ENDL;
    CIN>>数组[计数器]}COUT<< ENDL;
COUT<< ENDL;
对于(INT计数器= 1;计数器< =大小;反++){
    COUT<< 元素<<计数器<< 是&所述;&下;数组[计数器]<< 。 << ENDL;
    COUT<< ENDL;}COUT<< *冰:)!<< ENDL;
COUT<< ENDL;
返回0;
}


解决方案

这是未定义的行为。 UB有许多种。这里有几个:

1),这会踢你的狗。

2),它会重新格式化您的硬盘驱动器。

3)将工作没有问题。

在你的情况,你的编译器和你的平台上并在这个特别的日子,你看到的(3)。但尝试一下其他地方,你可能会得到(1),(2),或别的东西完全(最有可能的访问冲突)。

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;
}

解决方案

It's undefined behavior. UB comes in many flavors. Here are a few:

1) It will kick your dog.

2) It will reformat your hard drive.

3) It will work without a problem.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆