I have a GLUT program that allocates memory at startup. How do I deallocate this memory when the program exits?
If the user exits your program through some input that you can catch, such as a key press or menu selection, the answer is trivial. Simply free the resources in the appropriate input event handler. Usually, this question comes up because the user has killed the program through window frame controls, such as the Microsoft Windows Close Window icon in the upper right corner of the title bar. In this case, your program won’t get a GLUT event indicating the program is exiting. In fact, when the window is destroyed, glutMainLoop() simply calls exit(0). For simple resources such as memory deallocation, this should not be a problem. The OS will free any memory that the process was using. Of greater concern is prompting the user to save work or flushing data held in software buffers to files. When using C++, the simplest solution to this problem is to wrap your GLUT application inside of a C++ class and create it with global scope.