Sean
Sean

Reputation: 4525

delete dynamically allocated memory in openGL

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

Answers (3)

Nicol Bolas
Nicol Bolas

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

ronag
ronag

Reputation: 51253

Use smart pointers and you won't need to worry about it.

Upvotes: 1

Miguel Grinberg
Miguel Grinberg

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

Related Questions