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

使用GLC库在OpenGL中替换渲染文本时的段错误与重叠问题求助

Fixing Segmentation Fault & Overlapping Text in GLC/OpenGL Font Rendering

Hey, let's work through your font rendering issues step by step—both the segmentation fault and the overlapping text are fixable with some key adjustments to your code. Let's break down what's going wrong first, then look at the corrected version.

What's Causing the Problems?

  1. Repeated GLC Resource Creation (Segmentation Fault & Memory Leak)
    You're calling glcGenContext() and glcNewFontFromFamily() every single time you run drawString()—that's once per frame in your render loop. This creates hundreds of unmanaged context/font resources, which will eventually cause memory exhaustion and invalid memory access (the segmentation fault). On top of that, your variable scope is broken: main() declares local GLint ctx, myFont; but drawString() uses undeclared variables (which the compiler treats as implicit global ints), leading to mismatched types and uninitialized memory access.

  2. No Frame Buffer Clearing (Overlapping Text)
    You never clear the screen between frames. Each new render of your text gets drawn on top of the previous one, hence the overlapping instead of replacement.

  3. Redundant State Setup
    Setting glViewport, projection matrices, and GL_LINE_SMOOTH every frame is unnecessary and can lead to state conflicts. These only need to be configured once during initialization.

Corrected Code

Here's the fixed version with explanations for each change:

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

// Global variables to avoid scope mismatches (alternatively, pass them as parameters)
char* msg = "ABCD";
GLint ctx, myFont;

void drawString(char* name, int x, int y) {
    // Only handle per-frame rendering logic here—no resource creation
    glcContext(ctx);
    glcFont(myFont);
    
    glColor3f(1, 0, 0);
    glPushMatrix();
        glRasterPos3f(x, y, 0);
        glcScale(20, 20);
        glcRenderString(name);
    glPopMatrix();
}

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
    if (key == GLFW_KEY_E && action == GLFW_PRESS) {
        msg = "abcd";
    }
}

int main() {
    if (!glfwInit()) {
        exit(EXIT_FAILURE);
    }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    GLFWwindow* window = glfwCreateWindow(500, 500, "font rendering", NULL, NULL);
    if (!window) {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    if (GLEW_OK != glewInit()) {
        std::cout << "Failed to initialize GLEW" << std::endl;
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    // Initialize GLC resources ONCE during setup
    ctx = glcGenContext();
    glcContext(ctx);
    myFont = glcGenFontID();
    glcNewFontFromFamily(myFont, "Courier");
    
    // Set global OpenGL states once
    glEnable(GL_LINE_SMOOTH);
    glViewport(0, 0, 500, 500);
    
    // Configure projection matrix once
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, 500.0, 500.0, 0.0, -1.0, 1.0);
    
    // Reset modelview matrix to identity
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glfwSetKeyCallback(window, key_callback);
    glfwSwapInterval(1);

    while(!glfwWindowShouldClose(window)) {
        // Clear the frame buffer every frame to fix overlapping text
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // White background (adjust as needed)
        glClear(GL_COLOR_BUFFER_BIT);

        drawString(msg, 100, 100);

        glfwPollEvents();
        glfwSwapBuffers(window);
    }

    // Clean up GLC resources before exiting
    glcDeleteFont(myFont);
    glcDeleteContext(ctx);

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}

Key Changes Explained

  • Fixed Variable Scope: ctx, myFont, and msg are now global (or you could pass them as parameters to drawString() if you prefer avoiding globals) to ensure consistent access across functions.
  • One-Time Resource Setup: GLC context and font are created once during initialization, not every frame. We also clean them up with glcDeleteFont() and glcDeleteContext() before exiting to avoid memory leaks.
  • Frame Clearing: glClear() with a background color ensures each frame starts fresh, eliminating text overlap.
  • Optimized State Configuration: Global OpenGL states (viewport, projection matrix, line smoothing) are set once during setup instead of every frame, reducing overhead and state conflicts.

This should resolve both the segmentation fault and the overlapping text issue when you press the E key.

内容的提问来源于stack exchange,提问作者Pramay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:30:12