主返回后的分段错误 11

Segmentation Fault 11 after Main returns

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

我有一个很长的程序,有多个类,所以除非你需要,否则我不会发布它。但是在主要回报之后,我得到了一个细分错误。

使用 GDB,我可以看到此错误:

program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000002300103be8
0x00000001000035cc in std::_Rb_tree<std::string, std::string, std::_Identity, std::less,     std::allocator >::_S_right (__x=0x2300103bd0) at stl_tree.h:512
512       { return static_cast<_Link_type>(__x->_M_right); }

我对C++很陌生,所以这对我来说只是胡言乱语。谁能破译它?看起来我的一个 STL 容器可能导致问题?关于如何解决它的任何建议?

使用代码编辑:

好的,所以我已经将其隔离到这个 if 块中的某个地方 main ,这是我写的最后一件事,当我注释掉它时,程序运行良好。

else if(line.substr(0, 3) == "Rec") // Recieve 
  {       
      istringstream ss(line);
      string s; // output string
      string upc;
      string name;
      int amount;
      int count = 0;
      while(ss >> s) // go through the words in the line
      {
          count++;
          if(count == 2)
            upc = s;
          else if (count == 3)
          {
            istringstream isa(line.substr(20, 2));
            isa >> amount; //Parse the amount
          }
          else if (count == 4)
            name = s;
      }

      warehouses.find(name)->second.receive_food(upc, amount); //add the food to the warehouse
  }

为了澄清我们正在查看的line是以下格式:

Receive: 0984523912 7 Tacoma

warehouses是一张地图:map<string, a4::warehouse> warehouses; //all the warehouses.

这是仓库接收方法

void warehouse::receive_food(std::string upc, int amount)
{
    items.find(upc)->second.receive(amount);
    todays_transactions = todays_transactions + amount;
}

items在哪里std::map<std::string, food> items;

最后是食物接收方法

void food::receive(int amount)
{
    crates.push_back(crate(life, amount));
}

crates在哪里std::list<crate> crates;

crate

    class crate
{
    public:
        crate(int, int);
        ~crate();
        int life;
        int quantity;
};

看起来像内存损坏。 _Rb_tree表明该错误与通常实现为红黑树的std::map有关。如果不看到代码,很难说更多。我建议使用 Valgrind 来调试问题。

在查看您在更新中发布的代码后,我认为问题是您没有检查warehouses.find(name)是否返回有效的迭代器。如果找不到密钥,它可以返回map::end()

添加检查:

  map<string, a4::warehouse>::iterator it = warehouses.find(name);
  if (it != warehouses.end())
    it->second.receive_food(upc, amount);
  else ; // handle the case of a missing key

以及对map::find的其他调用的类似检查。