Titan
Titan

Reputation: 15

Segmentation Fault with G++

I am getting a segmentation error in one part of my program. I've tried a few different methods to get it to work but none have been successful. I debugged it with gdb and got:

Program received signal SIGSEGV, Segmentation fault. 0x000000363c49d56e in std::basic_string <char, std::char_traits <char>, std::allocator <char> >::assign(std::basic_string <char>, std::char_traits <char>,std::allocator <char> > const&) () from /usr/lib64/libstdc++.so.6

I am not sure what that debugging message means and I did not found anything useful when I searched. Can someone tell me why I am getting this error and how to fix it?

Here is the part of the program with the error.

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

Thanks in advance.

Upvotes: 0

Views: 1288

Answers (2)

R Sahu
R Sahu

Reputation: 206747

The value of x keeps increasing. You need to do something when x reaches 20.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

You're quite clearly going to overrun separated.

Use vectors, not arrays, and/or assert for the container sizes you expect during your algorithm. Then you will be able to see logic errors much quicker.

Upvotes: 1

Related Questions