iterator seg faults

I'm trying to create an asteroids game using OpenGL. I'm getting seg faults if I erase an element from a vector. Here's my main() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#include <GL/glut.h>
#include "Bullet.h"
#include "Ship.h"
#include "Asteroid.h"
#include <cmath>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

using namespace std;

const float DEG2RAD = M_PI/180;
const GLint windowDim = 20;
const GLint numOfBullets = 10;
const GLint maxNumOfAsteroids = 10;
const GLint largeRadius = 4;
const GLint mediumRadius = 2;
const GLint smallRadius = 1;
vector<Bullet> bullets;
vector<Asteroid> asteroids;
Ship ship;
int id = 0;

void constructNewAsteroid(const GLint R, int X, int Y)
{
  Asteroid asteroid;
	asteroid.generate(R);
	asteroid.setId(id++);
  asteroid.setPosX(X);
  asteroid.setPosY(Y);
  asteroid.setAngle(1 + rand() % 360);
	asteroid.setSpeedX(.001*cos(asteroid.getAngle()*DEG2RAD));
  asteroid.setSpeedY(.001*sin(asteroid.getAngle()*DEG2RAD));
  asteroids.push_back(asteroid);
  //cout << "three" << asteroids.size() << endl;
}

bool collision(Bullet bullet)
{
    vector<Asteroid>::iterator iter = asteroids.begin();

  while(iter != asteroids.end())
  {

    if(iter->checkForCollision(bullet.getPosX(), bullet.getPosY()))
    {
      if(iter->getRadius() == largeRadius)  //construct 2 medium sized asteroids in its place
      {
        float posX = iter->getPosX();
	float posY = iter->getPosY();
	asteroids.erase(iter);
        constructNewAsteroid(mediumRadius, posX+1, posY+1);
        constructNewAsteroid(mediumRadius, posX-1, posY-1);

	return true;
      }
      else if(iter->getRadius() == mediumRadius)  //construct 1 small asteriod in its place
      {
	float posX = iter->getPosX();
	float posY = iter->getPosY();
	asteroids.erase(iter);
				
        constructNewAsteroid(smallRadius, posX, posY);
				
	return true;
      }
      else
      {
        iter = asteroids.erase(iter);
	return true;
      }
    }
    else
      iter++;
  }
  
  return false;

}


void moveShip()
{
  ship.incrementPosX(ship.getSpeedX());
  ship.incrementPosY(ship.getSpeedY());

  if(abs(ship.getPosX()) > windowDim)
  {
    ship.setPosX(-1*ship.getPosX());
  }

  if(abs(ship.getPosY()) > windowDim)
    ship.setPosY(-1*ship.getPosY());

}

void moveAsteroids()
{
  for(int i=0; i<asteroids.size(); i++)
  {
    //asteroids[i].incrementPosX(asteroids[i].getSpeedX());
    //asteroids[i].incrementPosY(asteroids[i].getSpeedY());
	asteroids[i].move();

    if(abs(asteroids[i].getPosX()) > windowDim)
    {
      asteroids[i].setPosX(-1*asteroids[i].getPosX());
    }

    if(abs(asteroids[i].getPosY()) > windowDim)
      asteroids[i].setPosY(-1*asteroids[i].getPosY());
  }
}

void moveBullet(Bullet bullet)
{

  //GLfloat posX = -.001*cos(bullets[i].getAngle()*M_PI/180);
  //GLfloat posY = -.001*sin(bullets[i].getAngle()*M_PI/180);

    bullet.incrementPosX(bullet.getSpeedX());
    bullet.incrementPosY(bullet.getSpeedY());
    
    collision(bullet);
    //cout << bullets.size();
    //cout << numOfBullets << endl;
    //cout << bullets[0].getSpeedX() << endl;

}

void timer( int t )
{
  moveShip();
  moveAsteroids();

  for(vector<Bullet>::iterator iter = bullets.begin(); iter != bullets.end();)
  {
    //moveBullet(*iter);
    //iter->incrementPosX(iter->getSpeedX());
    //iter->incrementPosY(iter->getSpeedY());
		iter->move();
		if(collision(*iter))
			bullets.erase(iter);

    else if(abs(iter->getPosX()) > windowDim || abs(iter->getPosY()) > windowDim)
    {
        //if(!bullets.empty())
          bullets.erase(iter);
    }
    else
      iter++;
  }
  glutPostRedisplay();
  //glutTimerFunc( 1000, timer, 1 );
}

void init(void)
{
  glClearColor (0.0, 0.0, 0.0, 0.0);
  glShadeModel (GL_FLAT);
  srand(time(0));
	
  for(int i=0; i<1; i++)
  {
    Asteroid asteroid;
    asteroid.generate(largeRadius);
		asteroid.setId(id++);
    asteroids.push_back(asteroid);
  }
/*
  vector<Asteroid>::iterator iter;
  cout << asteroids.size() << endl;
  for(iter = asteroids.begin(); iter != asteroids.end(); iter++)
  {
    asteroids.erase(iter);
    cout << asteroids.size() << endl;
    if(asteroids.size() > 0)
      iter = asteroids.begin();
  }
*/


}

void display(void)
{
	glClear (GL_COLOR_BUFFER_BIT);
	glColor3f(1.0,1.0,1.0);
  glutTimerFunc(1, timer, 1 );
	glLoadIdentity();

  for(vector<Asteroid>::iterator iter = asteroids.begin(); iter != asteroids.end(); iter++)
  {
    iter->setSpeedX(.001*cos(iter->getAngle()*DEG2RAD));
    iter->setSpeedY(.001*sin(iter->getAngle()*DEG2RAD));
  }

	//move ship
	glPushMatrix();
	ship.draw();
  glPopMatrix();

  for(vector<Asteroid>::iterator iter = asteroids.begin(); iter != asteroids.end(); iter++)
  {
    glPushMatrix();
      iter->draw();
    glPopMatrix();
  }

  //move and draw bullet
  for(vector<Bullet>::iterator iter = bullets.begin(); iter != bullets.end(); iter++)
  {
    glPushMatrix();
      iter->draw();
    glPopMatrix();
  }

	glutSwapBuffers();
}

void reshape (int w, int h)
{
   glViewport (0, 0, (GLsizei) w, (GLsizei) h);
   glMatrixMode (GL_PROJECTION);
   glLoadIdentity ();
   gluOrtho2D(-windowDim,windowDim,windowDim,-windowDim);
	 //gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   //gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}

void specialKeys (int key, int x, int y)
{
   switch (key) {
      case GLUT_KEY_UP:
          //ship.incrementVelocity();
          ship.incrementSpeedX(.0001*cos(ship.getAngle()*DEG2RAD));
          ship.incrementSpeedY(.0001*sin(ship.getAngle()*DEG2RAD));

         glutPostRedisplay();
         break;

      case GLUT_KEY_LEFT:
				 ship.setAngle((ship.getAngle() - 2) % 360);
         glutPostRedisplay();
         break;
      case GLUT_KEY_RIGHT:
				 ship.setAngle((ship.getAngle() + 2) % 360);
         glutPostRedisplay();
         break;
		}
}

void keyboard(unsigned char key, int x, int y)
{
	switch(key)
	{
  case ' ':
    //speed of bullet when ship is not moving
    GLfloat initBulletSpeedX = .01*cos(ship.getAngle()*DEG2RAD);
    GLfloat initBulletSpeedY = .01*sin(ship.getAngle()*DEG2RAD);
    //bullet is 'active' so it will be drawn
    //bullets[i].setActive(true);
    //bullets[i].setAngle(ship.getAngle());
    Bullet bullet;
    bullet.setPosX(ship.getPosX());
    bullet.setPosY(ship.getPosY());
    bullet.setSpeedX(initBulletSpeedX + ship.getSpeedX());
    bullet.setSpeedY(initBulletSpeedY + ship.getSpeedY());
    bullets.push_back(bullet);

    //cout << "ship speed: " << ship.getSpeedX() << ' ' << ship.getSpeedY() << endl;

    break;
    glutPostRedisplay();
	}
}


int main(int argc, char** argv)
{
   glutInit(&argc, argv);
   glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
   glutInitWindowSize (500,500);
   glutInitWindowPosition (0, 0);
   glutCreateWindow (argv[0]);

   init();
   glutDisplayFunc(display);
   //glutIdleFunc(display);
   glutReshapeFunc(reshape);
	 glutSpecialFunc(specialKeys);
   glutKeyboardFunc(keyboard);
	 glutPostRedisplay();
   glutMainLoop();

   return 0;
}


The problem is on line 52. If I leave it the way it is it works fine. But if I try to move line 52 to line 55 I get a segmentation fault. If I leave line 52 I have to save the posX, posY values into variables before I erase the asteroid. If I moved line 52 to line 55 I would just be able to use iter->getPosX(), iter->getPosY() as arguments into the constructNewAsteroid() function. But like I said, if I do that I get a segmentation fault for some reason.

thanks,
mike
When you erase() it invalidates the iterator, but it returns the next valid iterator so you can use:

iter = asteroids.erase(iter);
You can't move the erase() past the constructNewAsteroid because the push_back within constructNewAsteroid is causing an internal reallocation in the vector and thus invalidating its iterators.

Also, see here:
http://www.cplusplus.com/forum/beginner/64854/
Last edited on
Topic archived. No new replies allowed.