[英]Keep getting this Segmentation Fault :11 error
我一直在我的代碼上出現這個錯誤。 幾分鍾前我的程序運行良好,突然間它不斷向我拋出這個錯誤。 我試圖通過在某些行之間使用cout << "here" << endl
來查找錯誤,有時它通常會在readInName()
函數內的for
循環中停止。 有時它會完全運行並打印出所有內容,甚至是"here"
。 其他時候我只會得到同樣的錯誤。
#include <fstream>
#include <string>
using namespace std;
// global variables
// these must be changed depending on the file.
const int SIZE = 10; // num of students
const int AMOUNTOFGRADES = 5; // num of tests per student
ifstream input;
// function declarations
void readInName();
float calculateAvgAndGrade(int count);
void header();
int readInGrades(int);
int main(){
header();
readInName();
return 0;
}
void readInName(){
string name[SIZE] = {""};
input.open("grade.txt");
int row,column;
int count;
for(row = 0; row < SIZE; row++){
input >> name[row];
cout << setw(10) << name[row] << ": ";
count = readInGrades(row);
cout << setw(5) << calculateAvgAndGrade(count) << endl;
}
input.close();
}
int readInGrades(int){
int r,c;
int grades[SIZE][AMOUNTOFGRADES] = {0};
int count = 0;
for(c = 0; c < AMOUNTOFGRADES; c++){
input >> grades[r][c];
cout << setw(5) << grades[r][c] << " ";
count = count + grades[r][c];
}
return count;
}
float calculateAvgAndGrade(int count){
return float(count)/AMOUNTOFGRADES;
}
void header(){
cout << setw(15) << " Names " << setw(20) << "Grades " << setw(18) << "Avg " << endl;
cout << setfill('-') << setw(53) << '-' << endl << setfill(' ');
}
在 readInGrades() 中, r
用作未初始化的索引以寫入 Grades grades[r][c]
,這是未定義的行為。 因此r
可能偶然具有任何值並寫入內存中的任意位置。 這有時會破壞堆棧並觸發分段錯誤。 解決此類錯誤的一個有用工具是AddressSanitizer ,通過使用 -fsanitize=address 編譯在 clang 或 gcc 中啟用,或者如果您使用的是 Xcode,則有一個選項。 另一個很棒的工具是valgrind 。
在我看來:
輸入>>成績[r][c];
r - 未初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.