【问题标题】:segmentation fault core dumped using ifstream使用 ifstream 转储分段错误核心
【发布时间】:2017-07-11 12:47:28
【问题描述】:

我编写了一个代码来读取一个文本文件并对其进行一些处理。它在我自己的 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 会导致分段错误以及如何解决它? 谢谢!

【问题讨论】:

  • 你的命令行参数是什么样的?
  • 一个minimal reproducible example 会很好...
  • 调试器非常适合这个。 gdb &lt;binary name&gt;, run &lt;program options&gt;, backtrace
  • @Brandon fragmentLength 为 4,overlapResidues 为 3。
  • @F.Hl 不在任何地方使用。这真的是失败的代码吗?另外什么是其他操作系统?你用什么编译器?

标签: c++ ifstream


【解决方案1】:

我怀疑对同一流的并发访问可能会引入数据竞争。您在 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;

    }

【讨论】:

  • 谢谢@Rohini Singh 我试过了,但又出现了同样的错误。
  • 我厌倦了在两个文件中都放了超过 1000 行。这里一切都很好我认为你应该使用 gdb 来调试核心它可能是中间问题你应该使用有效的字符串解析和错误处理使用例外
  • 我要求不赞成票的人解释反对票的原因
猜你喜欢
  • 2015-06-25
  • 2021-06-03
相关资源
最近更新 更多