【问题标题】:Segmentation Fault with G++G++ 的分段错误
【发布时间】:2014-03-27 02:02:38
【问题描述】:

我的程序的一部分出现分段错误。我尝试了几种不同的方法来让它工作,但没有一个成功。我用 gdb 调试了一下,得到:

程序收到信号SIGSEGV,分段错误。 来自/usr/lib64/libstdc++.so.6的std::basic_string <char, std::char_traits <char>, std::allocator <char> >::assign(std::basic_string <char>, std::char_traits <char>,std::allocator <char> > const&) ()中的0x000000363c49d56e

我不确定该调试消息的含义,并且在搜索时没有发现任何有用的信息。谁能告诉我为什么会收到此错误以及如何解决?

这是程序有错误的部分。

  std::string name, gift, input, token, compare;
  std::string giant[50], separated[20], individuals[20], items[20];
  int size, z = 0, x = 0, r =0;
  cout << "****************Opening file to read list.****************" << endl << endl;
  ifstream infile;
  infile.open("input.txt");

  while(!(infile.eof()))
  {
       for(size = 0; size < 20; size++)
       {
             getline(infile, giant[size]);
       }           
       for(z = 0; z < 20; z++) //I believe this loop is the problem.
       {
             std::istringstream identity(giant[z]); 
             while(getline(identity, token, '"'))
             {
                    separated[x] = token;
                    x++;
             }
       }
  }

提前致谢。

【问题讨论】:

  • 哪个学习资源教你写while(!(infile.eof()))
  • 核心发生在哪一行?可以用调试信息编译吗?
  • 在内部检查 x 可能很有用 while(getline(identity, token, '"')) { separator[x] = token; x++;}
  • 我们学习基本文件 I/O 时我的导师。
  • 这个问题似乎是题外话,因为它是关于要求其他人调试代码转储。

标签: c++ string gdb g++


【解决方案1】:

你很明显会超越separated

使用向量,而不是数组,和/或 assert 来表示您在算法中期望的容器大小。然后您将能够更快地看到逻辑错误。

【讨论】:

    【解决方案2】:

    x 的值不断增加。当x 达到 20 时,你需要做点什么。

    【讨论】:

    • x 的值为20 并访问separated[20] 时,会发生缓冲区溢出。
    猜你喜欢
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2013-08-17
    相关资源
    最近更新 更多