Search code examples
androidc++cocos2d-xcocos2d-x-3.0

Segfault when trying to access header declared member


I have a Cocos2d-x 3.14 project that I'm trying to migrate to 3.15, and it works perfectly for iOS, but it doesn't for Android. 3.14 works fine on both.

When running the 3.15 migrated version, I get a segfault when accessing a member that was declared in the header using this->member. If I add local variables it works fine.

Hpp file:

class GameBoard : public Layer
{
public:

    static cocos2d::Scene* createScene();
    virtual bool init();
    CREATE_FUNC(GameBoard);

    // background
    Sprite* background;
    void setupBackGround();

    ...
}

Cpp File:

void GameBoard::setupBackground() {

    cocos2d::Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    if (this->background == NULL) {
         doStuff();
    }
}

The line 'this->background' crashes. Does anyone have any idea why this might happen?


Solution

  • Turns out that in Cocos2d-x 3.15 (at least in our project) the 'applicationResized' function is being called before the initialization of the scene. Put this together with the fact that none of the pointers being used in the NULL checks in this applicationResized function were actually initialized as NULL, which was causing false if checks to pass.

    In that sense @πάνταῥεῖ was correct, 'this' (the GameBoard) was not properly instantiated at that point, but was pointing to random memory.