Sign in to follow this  
Numsgil

Memory leak with STL and Glut?

Recommended Posts

I'm running Visual Studio 2005 Professional Edition. After adding a std::list to my main function in my C++ program, I started getting memory leaks. I've isolated the problem to this code snippet:
#include <list>
#include <GL/glut.h>

#ifdef _MSC_VER
/* 
	Visual Studio has some unique mem leak detection
	abilities.  These enable it.  You'll still need 
	to call 
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
	at the start of the program.
*/
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif

int main(int argc, char *commands)
{
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

	int Window = glutCreateWindow("Lodestone Demo");	

	std::list<float *> Points; //comment this line out to make the memory leak go away??  Why does this work?

	glutMainLoop();

	//glutDestroyWindow(Window);
	
	return 0;
}

It uses Visual Studio's in-built leak detector, so it needs to be run in debug mode through Visual Studio's IDE. In the output window, it should show a leak of 24 bytes. The leak seems to be caused by declaring a list before calling glutMainLoop(); Commenting out either glut's main loop or the line declaring the list fixes the memory leak. Can someone help me determine exactly what's going on here? This shouldn't leak. Is glut maybe conflicting with Visual Studio's memory manager, giving a false positive? Does this problem still show up in other compilers (you'd have to replace the leak detection code in this sample with your own brand).

Share this post


Link to post
Share on other sites
I found I could solve the problem by putting everything in a different scope from the glutMainLoop. like this:

int main()
{
{
//...stuff
}

glutMainLoop();
}



So it's a dirty hack, but at least it works properly now.

Quote:
Original post by SiCrane
No, actually this is probably GLUT's fault. In most cases, when GLUT exits, it calls exit(), which does not properly call destructors in stack unwind. This is a bad thing. For more information see question 3.070 in the GLUT FAQ.


That makes sense, good to know I'm not crazy.

Quote:
Mike2343
You might want to try something like FreeGlut too, last time I checked (over a year ago so might have changed) Glut was no longer being supported.


Thanks, I'll give it a look.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this