【问题标题】:STL String ::length() SEGFAULTingSTL 字符串 ::length() SEGFAULTing
【发布时间】:2013-02-17 16:30:59
【问题描述】:
#include <iostream>
#include <string>
#include <vector>

/*
  Using STL's string class because the problem does not refer any
  limits regarding the number of characters per line.
 */

using namespace std;

int main()
{
  string line;
  vector<string> lines;
  while (getline(cin, line))
  {
    lines.push_back(line);
  }

  unsigned int i, u;
  unsigned int opening = 1; // 2 if last was opening, 1 if it was closing
  for (i = 0; i < (int) lines.size(); i++)
  {
    for (u = 0; u < (int) lines[u].length(); u++)
    {

    }
  }

  return 0;
}

我有一个只读取几行的简单代码(输入文件):

"To be or not to be," quoth the Bard, "that
is the question".
The programming contestant replied: "I must disagree.
To `C' or not to `C', that is The Question!"

但是,我发现它是 SEGFAULTing,因为它在第一行(第 4 个字符)读取了一个“”(空格)字符:

(gdb) run < texquotes_input.txt 
Starting program: /home/david/src/oni/texquotes < texquotes_input.txt

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b92533 in std::string::length() const () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6

我真的不明白为什么,我没有在循环内做任何事情,我只是在循环。

【问题讨论】:

  • 优秀的“小型完整可编译示例”。
  • 经验法则:如果 stdlib 中存在段错误,您可能正在读/写/删除不该读/写/删除的地方;)。

标签: c++ string stl segmentation-fault string-length


【解决方案1】:

我已经发现了问题。这是内循环:

for (u = 0; u < (int) lines[u].length(); u++)
{

}

应该是:

for (u = 0; u < (int) lines[i].length(); u++)
{

}

【讨论】:

    【解决方案2】:

    在另一个答案中,索引错字已经被发现。

    我想补充一点,使用基于范围的for 循环这类问题更难发生,因为循环更“隐含”:

    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    int main()
    {
      string line;
      vector<string> lines;
      while (getline(cin, line))
      {
        lines.push_back(line);
      }
    
      for ( const auto& currLine : lines )
      {
        for ( auto ch : currLine )
        {
          cout << ch;  
        }
        cout << '\n';
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      • 2015-08-17
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多