I have a list of pointers that reference time objects that need a turn to go in my game. This example has two TimeObject*
in the list. This code works until an item is removed from the list: when that happens the other one points to becomes an invalid address. Neither TimeObject
is deleted when this happens; only the pointer is removed from the list. What is causing this?
TimeUnlink()
is called in TimeObject::Tick()
. It is not a static, but the list is.
I'm using GCC 4.6.2 on Linux. The program is not threaded.
void TimeObject::TimeUnlink()
{
printf("Time unlink\n");
TimeObject::list_.remove(this);
timeobject_flags_.linked_ = 0;
}
void GameTime::GameTurn(uint16_t _time)
{
tick_ += _time;
for(std::list<TimeObject*>::iterator it = TimeObject::list_.begin(); it != TimeObject::list_.end(); ++it)
{
TimeObject *timeobject = *it;
printf("GameTurn %p\n", timeobject);
if(timeobject == NULL) { printf("continue\n"); continue; }
timeobject->time_ += _time;
if(timeobject->speed_ && timeobject->time_ >= timeobject->speed_)
{
while(timeobject->timeobject_flags_.linked_ && timeobject->time_ - timeobject->speed_ > 0)
{
timeobject->time_ -= timeobject->speed_;
if(timeobject->mapobject_)
{
timeobject->mapobject_->Tick();
}
}
}
}
}
Error output:
GameTurn 0xc1e048
GameTurn 0x696828
GameTurn 0xc1e048
GameTurn 0x696828
GameTurn 0xc1e048
GameTurn 0x696828
GameTurn 0xc1e048
Time unlink
GameTurn (nil)
continue
GameTurn 0xc1e030
Program received signal SIGSEGV, Segmentation fault.
0x00000000004059a1 in GameTime::GameTurn(unsigned short) ()