g++的分段错误

Segmentation Fault with G++

本文关键字:错误 分段 g++      更新时间:2023-10-16

我在程序的一部分中得到分段错误。我尝试了几种不同的方法来让它工作,但都没有成功。我用gdb调试它,得到:

程序收到信号SIGSEGV,分段错误。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

我不确定调试消息是什么意思,当我搜索时,我没有发现任何有用的东西。有人能告诉我为什么我得到这个错误,以及如何解决它?

下面是程序中出现错误的部分。

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

你很明显会超越separated

使用向量,而不是数组,和/或assert为您在算法期间期望的容器大小。然后,您将能够更快地看到逻辑错误。

x值不断增大。当x达到20时,你需要做点什么