Jump to content
  • Advertisement


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


CRASH! when removing last element in vector

This topic is 5827 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

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;
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

// 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

  • Advertisement

Important Information

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

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!