为循环导致随机分段C++
问题描述:
我的程序运行良好,直到我尝试添加一个简单的for循环,然后我得到一个seg故障。我会继续并发布主体,以便您可以看到:为循环导致随机分段C++
using namespace std;
int main(int argc, char* argv[]){
struct question questions[argc-1]; //Array of questions to be filled by loop.
int sizeOfQuestions = argc-1; //number of questions passed in at run time
int numLines = 0; //number of lines in file
for(int i=1;i<argc;i++){ //Test loop to make sure the command line file names are read in
std::cout << argv[i] << " says hello" << std::endl;
}
for(int count=0;count<sizeOfQuestions;count++){ //This loop places the information from the files into structs
char* fileName;
std::string word = argv[count+1];
word+=".txt";
strcpy(fileName, word.c_str());
std::fstream questionFile (fileName, std::fstream::in); //Open the file
if(questionFile.good()){
cout << "In File: \t" << fileName << endl;
setQuestionFileName(&(questions[count]),word);
getline(questionFile,questions[count].programNum);
getline(questionFile,questions[count].programDesc);
getline(questionFile,questions[count].programPoints);
getline(questionFile,questions[count].programInput);
questionFile.close();
}else{
cout << "Could not open file!!!" << endl;
}
}
sort(questions,questions+sizeOfQuestions);
display(questions[0]);
cout << "" << endl;
cout << "" << endl;
display(questions[1]);
return 0;
}
将显示它应该显示的内容。但是,当我更改代码的最后一节从
display(questions[0]);
cout << "" << endl;
cout << "" << endl;
display(questions[1]);
要:
for(int k=0;k<2;k++){
display(questions[k]);
cout << "" << endl;
cout << "" << endl;
}
我得到一个分段错误之后的第一个for循环其中说"says hello"
,这是为什么?即使我删除了display(),只是在循环中做了几个cout语句,它仍然会中断。
答
你有这些行
char* fileName;
...
strcpy(fileName, word.c_str());
但没有在任何地方你分配内存fileName
。
由于未初始化的局部变量(如fileName
)有不确定值,用起来不用初始化(像一个指针分配内存)导致未定义行为。
在这种情况下,你实际上并不需要这个fileName
指针。在C++ 11中,文件流构造函数已更改为接受std::string
(请参阅,例如this reference),如果您有较旧的库,则在打开文件时只需使用word.c_str()
。
因此,而不是跳过fileName
变量,只是做
std::ifstream questionFile (word);
或可能
std::ifstream questionFile (word.c_str());
那是什么原因呢?那很简单? – user2990286
@ user2990286是的,这是“那么简单”:) –
改变了一些事情,我正在工作,感谢这一点。欣赏它! – user2990286