[英]stack smashing terminates program
我正在學習 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 >> v;
myData[i] = v; // Direct assignment without validating i
// i needs to be validated before this assignment
我想指出以下幾點:
對於具有相同值的初始化,您不需要循環,因為std::array::fill()成員函數正是這樣做的。
例子:
std::array<int, 10> data;
data.fill( 1 );
您正在使用std::array
這意味着您至少在使用 C++11。 因此,對於數組遍歷,您可以像這樣使用 C++11 的range-for循環:
for ( const auto& i : data )
{
std::cout << i << ' ';
}
如果您還不熟悉auto 說明符,您可能想看看它。
我不知道你do-while
這里使用do-while
循環的原因。 您可以使用一個簡單的while
無限循環(用於學習目的)在無效索引輸入上使用if-else
在分配之前驗證索引來打破它。
例如:
while ( true )
{
// Print array here...
std::cin >> index;
if ( /* index is out of bounds */ )
{
std::cerr << "ERROR: Out-of-range index!\n";
break; // Exit from loop here on invalid index
}
else
{
std::cin >> value;
data[ index ] = value;
}
}
請看一下std::array::at()
成員函數,它執行邊界檢查並在違規時拋出異常。
我不確定你對這部分做了什么,因為std::cout
周圍的大括號在這里是多余的:
while(i >= 0 && i < myData.size()); // do-while ends here
{
cout << endl <<"Index out of range: Exit "<< endl;
}
也許,您將do-while
與while
循環混淆了。
請不要忘記將來格式化您的代碼。 使用您的 IDE 的代碼格式化功能,或者您也可以使用任何在線代碼格式化站點(例如http://format.krzaq.cc/ ),同時在 SO 上發布您的代碼。 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.