Hi there, I’m a newbie to c++ and having trouble with a particle system I’m attempting to write. I’m really inexperienced with pointers and memory allocation, aswell as STL so I am probably making a really simple error. I’m getting crashes after running my code for 30 seconds or so. Here’s a stripped down example of where my problem lies.
static void renderGL(std::vector<Particle *> & pVec) {
//--- Add new particle every frame, limit to 1000 ---
if(pVec.size() < 1000) {
Particle *p = new Particle(720, 450);
pVec.push_back(p);
}
std::vector<Particle *>::iterator iter;
//--- Iterate through vector and call particle class member function update() ---
for(iter = pVec.begin(); iter != pVec.end(); iter++) {
(*iter)->update();
}
//--- Iterate through vector, check particle class member function getLife() ---
//--- Delete particle from memory, then remove erase() from vector ---
for(iter = pVec.begin(); iter != pVec.end();) {
if((*iter)->getLife() == 0) {
delete (*iter);
iter = pVec.erase(iter);
} else {
++iter;
}
}
}
static void eventLoop() {
//--- Add 10 particles to vector begin with ---
std::vector<Particle *> pVec;
for(int i=0; i<10; i++) {
Particle *p = new Particle(720, 450);
pVec.push_back(p);
}
//--- Loop until exit ---
int done = 0;
while(!done) {
renderGL(pVec);
}
}
Basically I get a bad allocation error and signal 9 sigbrt which kills the application sometimes or hangs the entire system (OsX Tiger). I think I’m not correctly freeing the memory of a created Particle. I think I’m erasing the vector entry correctly though. This isn’t all the code, I’m happy to provide the source if it helps at all… I’d really appreciate any help, atm this is a big stumbling block I’m eager to get past and understand what’s going on.
