Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL String ::length() SEGFAULTing

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

I have that simple code that just reads over a few 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 that it is SEGFAULTing as it reads a ' ' (space) character on 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 can't understand why, I'm not doing anything inside the loop, I'm just looping.

like image 260
David Gomes Avatar asked Mar 03 '13 15:03

David Gomes


2 Answers

I already found the problem. It's the inner loop:

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

}

Should be:

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

}
like image 160
David Gomes Avatar answered Sep 26 '22 00:09

David Gomes


In another answer the index typo was already spotted.

I'd like to add that using range-based for loops those kinds of problems are more difficult to happen, since the loop is kind of 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';
  }
}
like image 36
Mr.C64 Avatar answered Sep 22 '22 00:09

Mr.C64