主返回后的分段错误 11
Segmentation Fault 11 after Main returns
我有一个很长的程序,有多个类,所以除非你需要,否则我不会发布它。但是在主要回报之后,我得到了一个细分错误。
使用 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
的其他调用的类似检查。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)