Removing a CCNode from std::list causes error in XCode

I’m having trouble deleting items from a `std::list` containing `CCNode` object. XCode gives me the following error when trying to `erase()` an element:

error: address doesn't contain a section that points to a section in a object file.

Or this error:

EXC_BAD_ACCESS code=2 at an assembly file.

And sometimes it crashes at:

ccGLBindTexture2D( m_pobTexture->getName() ); giving me an EXC_BAD_ACCESS.
Each time I run the application I get one of those errors.

The remove() method correctly removes the CCNode from the CCLayer, it disappears and the node count goes down by one. The problem is that the TestObject still remains in the testList list, eating up memory, cpu, and messing up the game.

I wrote a test case to reproduce the problem. Here it is:
@
testList = *new list;
testList.push_back(*new TestObject());
addChild(&testList.back());
testList.back().spawn();
testList.back().remove();

std::list::iterator test = testList.begin();
while (test != testList.end())
{
if(test->isRemoved){
testList.erase(test++);
}
}@

The TestObject class is simply a CCNode with the following remove() and spawn() methods added:

`TestObject::TestObject(){
sprite = *CCSprite::createWithTexture(MainScene::hostileship_tex);
}

void TestObject::spawn(){
    CCSize size = sprite.getTexture()->getContentSize();
    this->setContentSize(size);
    this->addChild(&sprite);
}

void TestObject::remove(){
    GameLayer::getInstance().removeChild(this, true);
}

`

The stacktrace XCode gives me just lists a couple of internal update and render functions of cocos2dx, giving me no idea whats causing the crash.

Be sure you’re always calling retain() on objects you are adding to your list and calling release() when you remove them (this is the disadvantage to not using a CCArray instead which does this automatically). Also you shouldn’t “new” anything that derives from CCObject (such as CCNode) and instead use one of their create() methods (which calls the object ‘init’ method and will set it to autorelease()).

See if that helps ya out :).

Thanks for your response. After countless hours of trying different combinations using CCArray, lists and vectors I came up with a new idea, that eventually worked.

I’m now using a vector to keep track of certain objects.
Upon contructiom I generate a random ID int.

When adding sprite I use addChildWithTag(object, id);

This way it works like a charm.

Awesome that you got a solution that works for you. Though, a little surprised that you couldn’t get CCArrays to work :(.