Hey all,
I'm getting a segfault when I try to access a vector of game objects, which I've checked and looks completely correct. Segfault only happens when the vector is empty (i.e. last shot is destroyed). Here's some code that demonstrates this:
if ( g_Shots.size() != 0 )
{
std::vector< SkyObject * >::iterator index = g_Shots.begin();
while ( index != g_Shots.end() )
{
SkyObject *obj = *index;
if ( obj )
{
// This is one location of a segfault
if ( obj->m_Param[1] == SHOT_PLAYER )
{
obj->m_PosY -= 4;
if ( obj->m_PosY < -32 )
{
if ( g_Shots.size() == 1 )
{
g_Shots.clear();
}
else
{
// This appears to be another
g_Shots.erase( index );
}
delete obj;
std::cout << "Shot destroyed.\n";
}
}
}
index++;
}
}
Note that even with the added g_Shots.size() == 0 checks, it still segfaults. The shots are being created with:
if ( CheckBtn( SDL_BUTTON_LEFT ) )
{
SkyObject *shot = new SkyObject();
shot->m_PosX = g_MouseX;
shot->m_PosY = g_MouseY;
shot->m_Param[0] = WPN_MACHINEGUN;
shot->m_Param[1] = SHOT_PLAYER;
g_Shots.push_back( shot );
std::cout << "Shot fired.\n";
}
GDB tells me that there may have been a double free or corruption, if that helps.
Can anyone help me figure out what's wrong? Everything looks right AFAIK. Thanks in advance!
[Edited by - fyhuang on February 12, 2005 4:43:42 PM]