I have a pretty long program with multiple classes so I wont post it unless you need it. But after main returns I get a segmentation fault.
Using GDB I can 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 looks like gibberish to me. Can anyone decipher it? It looks like one of my STL containers might be causing the issue? Any advice on how to fix it?
EDIT With Code:
Okay so I’ve isolated it down to somewhere in this if block of main, It was the last thing I wrote and when I comment it out the program runs 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 the line we are looking at is in this format:
Receive: 0984523912 7 Tacoma
warehouses is a map : map<string, a4::warehouse> warehouses; //all the warehouses.
Here is the warehouse receive method
void warehouse::receive_food(std::string upc, int amount)
{
items.find(upc)->second.receive(amount);
todays_transactions = todays_transactions + amount;
}
Where items is std::map<std::string, food> items;
And Finally the Food Receive method
void food::receive(int amount)
{
crates.push_back(crate(life, amount));
}
Where crates is std::list<crate> crates;
And a crate is
class crate
{
public:
crate(int, int);
~crate();
int life;
int quantity;
};
Looks like a memory corruption.
_Rb_treesuggests that the error has something to do withstd::mapwhich is usually implemented as a red-black tree. It is hard to say more without seeing code. I recommend using Valgrind to debug the issue.After looking at the code that you’ve posted in the update, I think that the problem is that you don’t check whether
warehouses.find(name)returns a valid iterator. It can returnmap::end()if the key is not found.Add a check:
and similar checks for other calls to
map::find.