【发布时间】:2018-09-15 03:42:20
【问题描述】:
我正在学习 C++,并被赋予创建一个程序的任务,该程序允许用户修改其中包含 10 个整数的数组。如果用户给出的索引超出范围程序将退出。程序适用于负数和范围内的所有数字。当我输入一个高于我得到的范围的 10 之类的数字时:
* 检测到堆栈破坏 *:已终止
我是新手,任何帮助将不胜感激。
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int, 10> myData; // creates array size 10
int i = 0;
int v = 0;
for (unsigned int n = 0; n < myData.size(); n++) // makes all elements 1
{
myData[n] = 1;
}
do
{
for (unsigned int a = 0; a < myData.size(); a++)
{
cout << myData[a] << " ";
}
cout << endl << "Input index: ";
cin >> i;
cout << endl << "Input value: ";
cin >> v;
myData[i] = v;
} while (i >= 0 && i < myData.size());
{
cout << endl << "Index out of range: Exit " << endl;
}
return 0;
}
当我运行程序时,我得到了这个:
1 1 1 1 1 1 1 1 1 1
Input index: 10
Input value: 4
Index out of range: Exit
*** stack smashing detected ***: <unknown> terminated
[1] 56 abort (core dumped) ./edit
【问题讨论】:
-
好的:
cin >> i。太好了,您已输入“11”。下一步:myData[i] = v;——太好了,你现在已经破坏了内存。您究竟在哪里做任何检查以确保输入的i值在范围内?是的,那部分稍后会出现,但我担心那匹马已经离开了谷仓,那时你已经破坏了记忆。你不能指望以随机的顺序做事,让计算机把事情整理出来,按正确的顺序做事。在您实际尝试访问数组 之前检查越界索引,而不是之后。跨度>
标签: c++ arrays for-loop do-while stack-smash