3

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

使用 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;
};
4

1 回答 1

1

看起来像内存损坏。_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

于 2013-02-01T20:51:14.530 回答