STL String :: length () SEGFAULTing

#include <iostream>
#include <string>
#include <vector>

/*
  Using STL 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;
}

I have that simple code that just reads across multiple lines (input file):

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

However, I found this to be SEGFAULTing as it reads the space character in the first line (4th character):

(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

I really cannot understand why, I am not doing anything inside the loop, I am just looping.

+5
source share
2 answers

I already found the problem. This is the inner loop:

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

}

Must be:

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

}
+6
source

In another answer, a typo of the index has already been noticed.

I would like to add that using loops forbased on the range of these issues is more complicated since the loop is more "implicit":

#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';
  }
}
+2
source

All Articles