title: Add and remove from a list in runtime
body: <p>I have a simulation program. In the main class of the simulation I am "creating + adding" and "removing + destroying" Agents.</p>
  
  <p>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. </p>
  
  <ul>
  <li>I don't know how is it possible that I have invalid Agents in my Loop.</li>
  <li><p>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). </p>
  
  <p>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.</p>
  
  <pre><code>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&lt;Agent*&gt;::iterator it = agents_.begin();
      while (it != agents_.end())
      {
          if (!(*it)-&gt;AllIntentionsFinished())
          {
              (*it)-&gt;step();
              it++;
          }
          else
          {
              (*it)-&gt;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 &lt; demand; i++)
      {
          Agent*  tmp  = new Agent(*this);
          agents_.push_back(tmp);
      }
  }
  
  Agent:
  
  bool Agent::AllIntentionsFinished()
  {
      return this-&gt;allIntentionsFinished_;  //bool flag will be true if all work is done
  }
  </code></pre></li>
  </ul>
  
  <p>1- Is it possible that VStudio 2012 optimization of Loops (i.e. running in multi-thread if possible) creates the problem?</p>
  
  <p>2- Any suggestions on debugging the code?</p>