Archived

This topic is now archived and is closed to further replies.

treezy

CRASH! when removing last element in vector

Recommended Posts

My goal was to write a simple space shooter game in a couple of days. Well after about an hour or so of programming, I tested my code and found an ugly bug. I''m storing all bullets in a vector, and everything works fine until I remove the last bullet from the vector, which causes my game to crash. Here''s my code for adding a bullet:
  
bullet->v_pos.x = player->v_pos.x + player->size_x / 2;
bullet->v_pos.y = player->v_pos.y + player->size_y / 2;
bullet->v_pos.z = player->v_pos.z - player->size_z;
bullet->alive = true;
bullet->v_vel.y = 1;
					BulletList.push_back(*bullet);
  
and here is my code for loopinh through the vector, updating bullets and checking for collision:
  
// traverse list of enemies

for(list<CEnemy>::iterator e_it = EnemyList.begin(); e_it != EnemyList.end(); e_it++) {

// traverse list of bullets

for(list<CBullet>::iterator b_it = BulletList.begin(); b_it != BulletList.end(); ++b_it) {

//if bullet is alive, check for collision

if(b_it->alive) {
// check for collision between bullet and enemy

if(Collision(b_it, e_it)) {
// reset enemy

e_it->Reset();
// kill bullet

b_it->alive = false;
// add score	

score += 3;
}
if(b_it->alive == false) {
// remove from list

b_it = BulletList.erase(b_it);
}
}
else { // remove from list

b_it = BulletList.erase(b_it);
}
//}

}
  
thanks for your suggestions...

Share this post


Link to post
Share on other sites
1. that''s not a vector, that''s a list, though they are interchangeable the way you are using them (very good)

2. The alive field seems to be complicating things, I would consider removing it and simply having only live bullets in your list at any time.

3. When you erase the last element you end up with b_it == end(), the for loop then calls ++b_it, a no-no. This is probably your bug.

Share this post


Link to post
Share on other sites
hey thanks for the reply.

lol sorry bout the mistake in my wording, the code had been sitting idle for so long on my hard drive that i forgot whether i used a vector or list (i obviously forgot to read my code when i posted).

and yea i ran it through the gdb debugger and it is crashing when calling ++b_it in the for loop. i''ll make some changes and get back. thanks for the advice.

Share this post


Link to post
Share on other sites