在传递给 glutDisplayFunc() 的函数中打印全局指针值时程序退出

program exits when printing global pointer values in the function passed to glutDisplayFunc()

我想从用户那里获取一些顶点 (x, y) 的输入。为了存储输入,我使用了指向整数的双指针。输入后,我正在检查输入是否正确存储。

输入已正确存储,但是,传递给 glutDisplayFunc() 的函数中未打印任何值,程序正在退出。

这是控制台输出:

Number of Vertices:3
Vertices (x, y):
100 0    // values entered by user
0 100
10 10
100 0    // values printed from takeInput()
0 100
10 10

Process finished with exit code -1073741819 (0xC0000005)    // maybe from myFunction()

这是我的代码:

#include <stdio.h>
#include <GL/glut.h>

GLint **points;
int n;

void takeInput(void) {
    printf("Number of Vertices:");
    scanf("%d", &n);

    GLint vertices[n][2], *ptrToVertices[n];
    printf("Vertices (x, y):\n");
    for (int i = 0; i < n; ++i) {
        scanf("%d%d", &vertices[i][0], &vertices[i][1]);
        ptrToVertices[i] = vertices[i];
    }
    points = ptrToVertices;

    /* check if input is stored correctly */
    for (int i = 0; i < n; ++i) {
        printf("%d %d\n", points[i][0], points[i][1]);
    }
}

void myFunction(void) {
    for (int i = 0; i < n; ++i) {
        printf("%d %d\n", points[i][0], points[i][1]);
    }
    // todo
}

void doGlutStuff(int argc, char **argv, char *title, void (*fun)(void)) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowPosition(0, 0);
    glutInitWindowSize(1000, 1000);
    glutCreateWindow(title);
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(-500.0, +500.0, -500.0, +500.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0, 0.0, 0.0);
    glutDisplayFunc(fun);
    glutMainLoop();
}

int main(int argc, char **argv) {
    takeInput();
    doGlutStuff(argc, argv, "My Title", myFunction);
    return 0;
}

顺便说一下,这就是我编译代码的方式:

gcc myCode.c -lopengl32 -lfreeglut -lglu32

您正在将指向局部变量 (ptrToVertices) 的指针存储到全局变量 (points) 中。一旦 takeInput returns、ptrToVertices 不再存在,您存储的指针将悬空。 (在这种情况下,它指向将被覆盖和重用的堆栈内存。当你在 myFunction 中取消引用 points 时,你有导致崩溃的未定义行为。

一个解决方案是使用 malloc 为您的顶点分配 space 而不是使用局部变量。