user10110573
user10110573

Reputation:

Exception thrown at 0x00000000 in Project0_opengl.exe: 0xC0000005: Access violation executing location 0x00000000

I'm writing right code but the compiler throws an error. The error says that the mistake is on glGenBuffers but I've copied it from the official website. Where is my mistake?

#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <stdio.h>

int main(void)
{
    GLFWwindow* window;
    glewExperimental = GL_TRUE;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

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

    GLuint buf;
    glGenBuffers(1, &buf);
    glBindBuffer(GL_ARRAY_BUFFER, buf);
    glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), pos, GL_STATIC_DRAW);

    if (glewInit() != GLEW_OK)
        printf("Error\n");

    printf("%s", glGetString(GL_VERSION));

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

Upvotes: 1

Views: 3604

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

glewInit() has to be called after the OpenGL context is made current, after glfwMakeContextCurrent.
But it has to be called before any OpenGL instruction. See also Initializing GLEW:

// [...]

/* Make the window's context current */
glfwMakeContextCurrent(window);

glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
    printf("Error\n");

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

GLuint buf;
glGenBuffers(1, &buf);
glBindBuffer(GL_ARRAY_BUFFER, buf);
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), pos, GL_STATIC_DRAW);

// [...]

Note, the instructions like glGenBuffers are function pointers. These pointers are initialized to NULL. glewInit() assigns the address of the function to those pointers.
When you try to call the function, before the initialization, this causes:

Access violation executing location 0x00000000

Upvotes: 2

Related Questions