Search code examples
c++pointersaccess-violationassimp

Returning a pointer messes up the object (access violation)


I'm fiddling around with assimp and C++, and I wrote a simple function to load a scene from a file. However, when I try to return the pointer, the object gets messed up and I get access violation if I try to retrieve member data. This snippet should demonstrate the case:

const aiScene* ResManager::loadScene(const std::string& pFile)
{
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(pFile, aiProcessPreset_TargetRealtime_MaxQuality);
    if(!scene)
    {
        printf("%s\n", importer.GetErrorString());
        return 0;
    }

    // If I break the debug here, 'scene' is valid
    return scene;
}

void ResManager::loadFromFile(const std::string& pFile)
{
    const aiScene* scn = loadScene(pFile);
    // If I break the debug here, 'scn' contains gibberish
}

I think I've missed something essential here about pointers and consts and such. Any ideas?


Solution

  • As it seems importer destructs when the function ends and therefore the object scene does not point to a valid pointer anymore. I think that dynamically allocating importer with

       Assimp::Importer *importer = new Assimp::Importer; 
    

    should do the trick.

    You should later on destroy this object with

    delete importer;