Jump to content

  • Log In with Google      Sign In   
  • Create Account

SDL C++ Program crashing


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 LewisDe   Members   -  Reputation: 105

Like
0Likes
Like

Posted 06 May 2013 - 05:18 AM

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, 06 May 2013 - 05:20 AM.


Sponsor:

#2 Álvaro   Crossbones+   -  Reputation: 13317

Like
1Likes
Like

Posted 06 May 2013 - 06:00 AM


//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, 06 May 2013 - 06:02 AM.


#3 kidman171   Members   -  Reputation: 498

Like
0Likes
Like

Posted 06 May 2013 - 06:01 AM

[edit] Alvaro beat me to it.


Edited by kidman171, 06 May 2013 - 06:02 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS