You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GLFW和GLAD时如何修复‘Access violation executing location’错误

OpenGL程序触发0xC0000005访问违例异常的解决方法

遇到的异常

Exception thrown at 0x0000000000000000 in OpenGL project.exe: 0xC0000005: Access violation executing location 0x0000000000000000.

用户代码

#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>

int main()
{
    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window{ glfwCreateWindow(800, 800, "Win", NULL, NULL) };

    if (window == NULL)
    {
        std::cout << "Doesn't work";
        glfwTerminate();
        return -1;
    }

    gladLoadGL();
    glfwMakeContextCurrent(window);

    glViewport(0, 0, 800, 800);

    glClearColor(50.0f, 1.3f, 1.7f, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glfwSwapBuffers(window);

    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

问题分析与修复步骤

核心问题:Glad初始化顺序错误

Glad需要绑定当前的OpenGL上下文才能正确加载OpenGL函数指针。原代码先调用gladLoadGL()再绑定上下文,导致Glad无法获取有效环境,加载的函数指针全为空,调用glClearColor、glClear等OpenGL函数时直接触发空指针访问违例。

具体修复动作

  1. 调整初始化顺序:必须先调用glfwMakeContextCurrent(window)绑定上下文,再执行Glad初始化
  2. 增加初始化校验:gladLoadGL()返回非0表示初始化成功,失败时需终止程序
  3. 修正颜色参数范围:glClearColor的RGBA参数必须在0.0f到1.0f之间,超出范围会被OpenGL自动截断,建议手动修正为合法值
  4. 迁移渲染逻辑到主循环:确保窗口持续刷新,避免仅渲染一次后无更新

修复后的代码

#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>

int main()
{
    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window{ glfwCreateWindow(800, 800, "Win", NULL, NULL) };

    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }

    // 先绑定OpenGL上下文
    glfwMakeContextCurrent(window);

    // 初始化Glad并检查结果
    if (!gladLoadGL())
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        glfwTerminate();
        return -1;
    }

    glViewport(0, 0, 800, 800);

    while (!glfwWindowShouldClose(window))
    {
        // 渲染逻辑放入循环,保证持续刷新
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // 修正为合法颜色范围
        glClear(GL_COLOR_BUFFER_BIT);
        
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

内容的提问来源于stack exchange,提问作者Mr. Margarine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:33:10