Jump to content
  • Advertisement
Sign in to follow this  
LewisDe

SDL C++ Program crashing

This topic is 2045 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Edited by LewisDe

Share this post


Link to post
Share on other sites
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. Edited by Álvaro

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!