Search code examples
openglexc-bad-access

OpenGL: Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)


I have an array of points to be drawn as a triangle. Before placing them on the screen, I'm using a function to translate their position. However, calling a translate function on the array causes the above error to show up.

    float positions[6] = {
    -0.5f, -0.5f,
    0.0f, 0.5f,
    0.5f, -0.5f
};

//Basic Translate function
void basicTranslate(float Tx, float Ty){
    for(int i=0; i<sizeof(positions); i++){
        if(i % 2 == 0)
            positions[i] += Tx;
        else
            positions[i] += Ty;
    }
}

The error occurs when I translate the function before dealing with my buffers and vertex array

    basicTranslate(2, 1);

    unsigned int buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), positions, GL_STATIC_DRAW);
    GLuint vao = 0;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

Solution

  • sizeof(positions) gives the size of the data type float[6] in bytes, which is 4*6=24.
    See sizeof operator

    Change the condition in the loop to solve the issue:

    for(int i=0; i<6; i++)
    

    In C++ I would recommend to use std::vector or std::array, both provide a size() method, which returns the number of elements in the container:

    #include <vector>
    
    std::vector<float> positions = {
        -0.5f, -0.5f,
         0.0f,  0.5f,
         0.5f, -0.5f
    };
    
    void basicTranslate(float Tx, float Ty)
    {
        for(size_t i=0; i<positions.size(); i++)
            positions[i] += (i % 2 == 0) ? Tx : Ty;
    }