I have a simulation program. In the main class of the simulation I am "creating + adding" and "removing + destroying" Agents.
The problem is that once in a while (once every 3-4 times I run the program) the program crashes because I am apparently calling a function of an invalid agent in the main loop. The program works just fine most of the time. There are normally thousands of agents in the list.
- I don't know how is it possible that I have invalid Agents in my Loop.
It is very difficult to debug the code because I receive the memory exception inside the "Agent::Step function" (which is too late because I cannot understand how was the invalid Agent in the list and got called).
When I look into the Agent reference inside the Agent::Step function (exception point) no data in the agent makes sense, not even the initialized data. So it is definitely invalid.
void World::step() { AddDemand(); // run over all the agents and check whether they have remaining actions // Call their step function if they have, otherwise remove them from space and memory list<Agent*>::iterator it = agents_.begin(); while (it != agents_.end()) { if (!(*it)->AllIntentionsFinished()) { (*it)->step(); it++; } else { (*it)->removeYourselfFromSpace(); //removes its reference from the space delete (*it); agents_.erase(it++); } } } void World::AddDemand() { int demand = demandIdentifier_.getDemandLevel(stepCounter_); for (int i = 0; i < demand; i++) { Agent* tmp = new Agent(*this); agents_.push_back(tmp); } } Agent: bool Agent::AllIntentionsFinished() { return this->allIntentionsFinished_; //bool flag will be true if all work is done }
1- Is it possible that VStudio 2012 optimization of Loops (i.e. running in multi-thread if possible) creates the problem?
2- Any suggestions on debugging the code?