Reputation: 4525
I use C++ and and freeglut, and want to know how to delete the dynamically allocated memory using new
. I need to free the memory when closing the window. Where should I put this delete pointer
? before glutMainLoop()
?
*Update*.
For example, I use int *ptr = new int[n]
to store the vertex coordinates, and did not use class in the code. So I have to call delete
in the main()
to free the memory. I understand that I can use vector to do the same thing. But in my case, if I have to use new
, how can I deallocate the memory?
Upvotes: 1
Views: 1380
Reputation: 473537
The old form of GLUT made it so that your program's execution never returned from the call to glutMainLoop
. FreeGLUT gets rid of this, but only if you specifically ask for it before calling glutMainLoop
:
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
This means that, when you eventually call glutLeaveMainLoop
, FreeGLUT will continue from where glutMainLoop
was called, just like a regular function call.
So if you allocate memory before glutMainLoop
, you can delete that memory afterwards.
That being said:
I use int
*ptr = new int[n]
to store the vertex coordinates
Why isn't that a std::vector<int> mem(n);
instead of a pointer? You can still get a pointer to the memory by doing &mem[0]
. And it will clean up after itself.
Upvotes: 3
Reputation: 67509
See question 3.0.70 in the OpenGL GLUT FAQ. Short answer is use an exit handler installed via the atexit() call.
Upvotes: 2