I want to take input from user some vertices (x, y). For storing the input, I am using double pointer to integer. After taking input, I am checking if the input is stored correctly.
The input is stored correctly, however, no values are printed in the function passed to glutDisplayFunc()
and the program is exiting instead.
This is the console output:
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()
This is my code:
#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;
}
By the way, this is how I am compiling my code:
gcc myCode.c -lopengl32 -lfreeglut -lglu32
You're storing a pointer to a local variable (ptrToVertices
) into a global (points
). Once takeInput
returns, ptrToVertices
no longer exists and the pointer you stored will be left dangling. (In this case it points to stack memory that will be overwritten and reused. When you dereference points
in myFunction
, you have Undefined Behavior which results in your crash.
One solution would be to use malloc
to allocate space for your vertices instead of using local variables.