Search code examples
copengl

OpenGL function calls seemingly affecting unrelated data


I have written some code that prints a pointer "playerFaces" before and after calling some OpenGL functions:

Object* object = game->scene.worldObjects[0];
Face* playerFaces = NULL;
int playerFaceCount = 0;
traverseBSP(object->collisionMesh, currentCamera->position, &playerFaces, &playerFaceCount);
printf("PF: %p\n", playerFaces);

glDepthMask(GL_TRUE);
glGenBuffers(GL_ARRAY_BUFFER, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);

printf("PF: %p\n", playerFaces);

The function traverseBSP is included (if relevant):

void traverseBSP(BSPNode* node, vec3 position, Face** faceBuffer, int* faceCountBuffer)
{
    if (node->front == NULL && node->back == NULL)
    {
        //leaf node... allocate memory to faceBuffer and fill it
        printf("fb** = %p\n", faceBuffer);
        printf("fb* = %p\n", *faceBuffer);
        *faceBuffer = (Face*)malloc(node->faceCount * sizeof(Face));
        printf("fb* after malloc  = %p\n", *faceBuffer);
        for (int i = 0; i < node->faceCount; i++)
        {
            (*faceBuffer)[i] = node->faces[i];
        }
        *faceCountBuffer = node->faceCount;
        return;
    }

    Plane np = node->splittingPlane;
    float d = np.normal.x * position.x + np.normal.y * position.y + np.normal.z * position.z + np.distance;
    if (d > 0)
    {
        traverseBSP(node->front, position, faceBuffer, faceCountBuffer);
    }
    else
    {
        traverseBSP(node->back, position, faceBuffer, faceCountBuffer);
    }
}

My intended output would be something to the effect of:

fb** = 0x723a97467e40
fb* = (nil)
fb* after malloc  = 0x519000038e80
PF: 0x519000038e80
PF: 0x519000038e80

My actual output is:

fb** = 0x723a97467e40
fb* = (nil)
fb* after malloc  = 0x519000038e80
PF: 0x519000038e80
PF: 0xd0000000c

Why might playerFaces be changing when I haven't explicitly done anything to change it? How do I debug this and fix the problem?

Edit: I know that I am meant to call glGenBuffers(1, &VBO), and changing it fixed my problem, but I am still curious why this would cause playerFaces to become 0xd0000000c, so any explanation is appreciated.


Solution

  • GL_ARRAY_BUFFER is a constant with the predefined value of 0x8892.

    Your call glGenBuffers(GL_ARRAY_BUFFER, &VBO); this tries to allocate roughly 32k VBOs and writes their handles in VBO[0] (also known as *VBO), VBO[1],...

    You did not show where VBO lives relative to your stack, but scribbling over 128kb of memory is bound to cause problems...