分段故障核心使用 IF流转储

segmentation fault core dumped using ifstream

本文关键字:IF 转储 故障 核心 分段      更新时间:2023-10-16

我写了一个代码来读取一个文本文件并对其进行一些处理。它在我自己的PC和另一个Linux系统上正常工作。但是,当我在不同的 Linux 系统上运行它时,我收到"ifstream"命令的"分段错误(核心转储("错误。我检查了文本文件,如果它太小(例如两行(,cose 工作正常,但是当文件较大(例如 20 行(时,它会崩溃并出现分段错误错误。

导致错误的代码段:

int ExtractFragments(int fragmentLength, int overlappingResidues)
{
string line = "", lines = "", interfaceFileName = "";
ifstream interfaceList("tempInterfaceList.txt"); 
if (interfaceList)
{
bool errFlag = false;
while (getline(interfaceList, interfaceFileName))   
{
cout << endl << "interfaces/" << interfaceFileName;
ifstream interfaceFile("interface.txt");    //This line crashes
if (interfaceFile)
cout << "nHello";
}
}
return 0;
}

任何想法为什么这个ifsream会导致分段错误以及如何解决它? 谢谢!

我怀疑 对同一流的并发访问可能会引入数据争用。 您正在以输入模式打开一个文件 while 循环在那里,您必须处理异常

int ExtractFragments(int fragmentLength, int overlappingResidues)
{
ifstream interfaceList("tempInterfaceList.txt"); 
interfaceList.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
try
{
if ( interfaceFile.fail() ) 
{
return -1;
}
bool errFlag = false;
while (getline(interfaceList, interfaceFileName))   
{
cout << endl << "interfaces/" << interfaceFileName;
ifstream interfaceFile("interface.txt");    //This line crashes
if (interfaceFile)
cout << "nHello";
}
}
catch(std::ifstream::failure &FileExcep)
{
cout<<FileExcep.what()<<endl;
return -1;
}
catch(...)
{
cout<< "other exception thrown"<<endl
return -1;
}
return 0;
}