SDL C++ Program crashing

Started by
1 comment, last by kidman171 10 years, 11 months ago

I have a bunny who shoots bullets. To ensure that resources aren't being depleted, the game erases that bullet from a vector of bullets when the bullet comes off the screen (when its x value is less than zero). However, whenever the game erases the obsolete bullet, the game ends abruptly. I think this problem has something to do with when the sprite resources are freed. Can anyone please help... sad.png

Code: http://pastebin.com/wG6rRqa8

The key lines to acknowledge are lines 441 and the projectile class

Advertisement


//THIS DELETES THE REDUNDANT BULLETS
void handleProjectiles()
{
   if( !allProjectiles.empty() )
   {  
      std::vector<projectile>::iterator it = allProjectiles.begin();
     
      for( ; it != allProjectiles.end(); it++ )
      {
           it->x += it->velocity;    
           it->show();
           
           if( it->x + it->w < 0 )
           {
               allProjectiles.erase( allProjectiles.begin(), it );
           }
      }
   }
}



That code is messed up. Whenever you find a bullet that satisfies certain conditions, you erase all the previous bullets in the vector. This will move all the remaining bullets to the beginning of the vector, and it will invalidate the iterator `it' (in a common implementation vector iterators are pointers, and you now have a pointer possibly pointing past the end of the vector, and now you won't hit the loop's terminating condition ever, so eventually it will point past the allocated block).

A clean solution to this problem is the erase-remove idiom.

[edit] Alvaro beat me to it.

This topic is closed to new replies.

Advertisement