Segmentation fault 11 after returning Main
I have a fairly long program with several classes, so I won't post it if you don't need it. But after basic returns, I get a segmentation fault.
Using GDB I see this error:
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); }
I'm very new to C ++, so this just sounds like gibberish. Can anyone decipher it? It looks like one of my STL containers might be causing the problem? Any advice on how to fix this?
EDIT With code:
Ok, so I isolated it somewhere in this block main
. This was the last thing I wrote and when I comment it the program works fine.
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
}
To clarify line
what we are looking at in this format:
Receive: 0984523912 7 Tacoma
warehouses
is the display: map<string, a4::warehouse> warehouses; //all the warehouses.
Here is the method to get the store
void warehouse::receive_food(std::string upc, int amount)
{
items.find(upc)->second.receive(amount);
todays_transactions = todays_transactions + amount;
}
Where items
isstd::map<std::string, food> items;
Finally, the eating method
void food::receive(int amount)
{
crates.push_back(crate(life, amount));
}
Where crates
isstd::list<crate> crates;
And crate
there is
class crate
{
public:
crate(int, int);
~crate();
int life;
int quantity;
};
source to share
Looks like memory corruption. _Rb_tree
suggests the error has something to do with std::map
, which is usually implemented as a red-black tree . It's hard to say more without seeing the code. I recommend using Valgrind to debug the problem.
After looking at the code you posted in the update, I think the problem is that you are not checking if a warehouses.find(name)
valid iterator is returning . It can return map::end()
if the key is not found.
Add check:
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
and similar checks for other calls map::find
.
source to share