Tuesday, June 1, 2010

Segmentation fault with c++ vector

Ever been in a situation where you got a seg. fault when you tried to push_back a pointer into the vector? What's more, you have a useless log file with no clues whatsoever. I had the same issue when i was working on an assignment with deadline in 2 hours. After whacking my head for 1-2 hours, I finally found a way to resolve the issue.

I was working on "simple ecosystem" project. The code where new fishes are created and added to the ecosystem seg. faulted. Take a look, I cut down unnecessary things to keep this example simple.
for (vector::iterator it = vecPossiblePositions.begin(); it!=vecPossiblePositions.end(); ++it)
{
//create a new fish..
Fish *f = new Fish();
f->setPosition(it->getX(), it->getY());

//This method does a push_back
//operation on some vector
ecosystem->addEcosystemObject(f);
}
If i comment out ecosystem->addEcosystemObject(f) line, then it runs without seg. fault. Apparently, the line Fish *f = new Fish() was causing the problem. So here's what i did.
Fish *f = NULL;
for (vector::iterator it = vecPossiblePositions.begin(); it!=vecPossiblePositions.end(); ++it)
{
//create a new fish..
f = new Fish();
f->setPosition(it->getX(), it->getY());

//This method does a push_back
//operation on some vector
ecosystem->addEcosystemObject(f);
}
and that fixed the problem! I have no idea why it worked. So, today's lesson of the day is "Keep the damn ptr declarations outside loops"

No comments:

Post a Comment