Search code examples
c++openglassimp

Access violation in OpenGL


I'm trying to verify if my vector is filled with some data but when I try to print a string, it the program gives the "Access violation reading location 0x00000010" error.

Here is my code:

for (unsigned int i = 0; i < mMeshes.size(); ++i) {
        InitMesh(i, mScene->mMeshes[i], Positions, TexCoords, Normals, VertexBones, Indices);
    }

    std::cout << mBones[mBoneMap["forearm.L"]].Name << "\n";

It stops at the cout. And here is my InitMesh function, from which the cout is executed correctly:

for (unsigned int i = 0; i < pMesh->mNumBones; ++i) {
    std::string BoneName = pMesh->mBones[i]->mName.data;
    int BoneIndex = 0;

    if (mBoneMap.find(BoneName) == mBoneMap.end()) {
        BoneIndex = mNumBones;
        mNumBones++;
        BoneInfo bi;
        mBones.push_back(bi);
    }
    else {
        BoneIndex = mBoneMap[BoneName];
    }

    mBoneMap[BoneName] = BoneIndex;
    mBones[BoneIndex].Name = BoneName;
    std::cout << mBones[i].Name << "\n";
    AiToGLM(pMesh->mBones[i]->mOffsetMatrix, mBones[BoneIndex].OffsetTransform);

    for (unsigned int j = 0; j < pMesh->mBones[i]->mNumWeights; ++j) {
        unsigned int VertexID = mMeshes[MeshIndex].BaseVertex + pMesh->mBones[i]->mWeights[j].mVertexId;
        VertexBones.at(VertexID).Add(i, pMesh->mBones[i]->mWeights[j].mWeight);
    }
}

The BoneInfo is a struct with two matices and a string called Name. The vector which holds the BoneInfos is in the header file:

struct BoneInfo {
std::string Name;
glm::mat4 OffsetTransform;
glm::mat4 FinalTransform;};

private:
    std::vector<BoneInfo> mBones;
    std::map<std::string, int> mBoneMap;
    int mNumBones = 0;

Solution

  • I don't see anything specifically wrong in this code. Unfortunately when in C++ you get a segfault in a given line it doesn't mean that the line is doing anything wrong, because the problem could have happened millions of executed instructions before and who is crying is just the victim that finds its data corrupted.

    In this case a memory read error when printing a string means that the string memory has been overwritten by someone. My experience says that this probably happened because of an out-of-bounds access from an array or because an object that was already destroyed was used again because there was a pointer still pointing to it (or because you're printing a data structure that has been already deallocated, of course).

    You should try to recompile with the debug version of the standard library that checks every array dereference and also adds a lot of checking on memory for write-after-deallocation errors. The program will run dog slow, but probably will point you to the real bad code that is corrupting memory.