STL字符串::length()导致段错误

5
#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!"

然而,我发现在读取第一行(第四个字符)的空格时,程序会出现SEGFAULT错误:
(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

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


2
优秀的“小而完整的可编译示例”。 - Mats Petersson
经验之谈:如果在stdlib中出现段错误,那么你很可能正在读取/写入/删除不应该操作的位置;) - Red XIII
2个回答

6

我已经找到问题所在了。是内部循环:

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

}

Should be:

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';
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接