简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM