Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SIGTRAP on delete[] with small arrays

Tags:

c++

A weird SIGTRAP error appears in a C++ OpenGL program of mine. First, a float array with the new[] operator is created like so:

std::vector<ObjFace> faces = readObjFile("sphere.obj");
vertexBufferSize = faces.size() * 24;
auto* vertexBuffer = new GLfloat[vertexBufferSize];

Then, the array is filled like this:

    for (int i{ 0 }; i < faces.size(); ++i) {
        for (int j{ 0 }; j < 4; ++j) {
            vertexBuffer[i*24 + j*8] = faces[i].corners[j][0];
            vertexBuffer[i*24 + j*8 + 1] = faces[i].corners[j][1];
            vertexBuffer[i*24 + j*8 + 2] = faces[i].corners[j][2];
            vertexBuffer[i*24 + j*8 + 3] = 1.0f;
            vertexBuffer[i*24 + j*8 + 4] = (faces[i].normals[j][0] + 1) / 2;
            vertexBuffer[i*24 + j*8 + 5] = (faces[i].normals[j][1] + 1) / 2;
            vertexBuffer[i*24 + j*8 + 6] = (faces[i].normals[j][2] + 1) / 2;
            vertexBuffer[i*24 + j*8 + 7] = 1.0f;
        }
    }

And it is then used with the glBufferData Macro and deleted afterwards:

glBufferData(GL_ARRAY_BUFFER, vertexBufferSize * sizeof(GLfloat), vertexBuffer, GL_STATIC_DRAW);

delete[] vertexBuffer;
vertexBuffer = nullptr;

For some reason the program will sometimes crash on a SIGTRAP error (debug mode) or with exit code -1073740940 (0xC0000374) (regular execution). I also made sure that vertexBuffer is not a nullpointer.

This problem only occurrs if the array size is relatively small. For bigger sizes, it works without a problem. To get it working with smaller sizes, I must not use new[] and delete[] - but then it will crash on bigger arrays because they take up too much space. Can someone explain to me what is going on here?

like image 892
be-rty Avatar asked Oct 28 '25 01:10

be-rty


1 Answers

You write 32 floats per face but you seem to have thought you were only writing 24. You're allocating 24 floats per face and skipping forward 24 floats to get to the next face, but you're actually writing 32 floats per face, because you're writing 8 floats per vertex and 4 vertices per face. So you always end up writing an extra 8 floats after the end of the array.

like image 115
user253751 Avatar answered Oct 29 '25 15:10

user253751