In Microsoft Visual C++ (VS 2008/2010) using a number of Standard Template Library containers like std::set or std:vector you will run into memory leaks with this:
#include <set>
#include <stdlib.h>
#include <crtdbg.h>
#define _CRTDBG_MAP_ALLOC
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
printf("I'm leaking\n");
std::set<int> s;
_CrtDumpMemoryLeaks();
return 0;
}
After you run the program, you’ll get some output like this:
Detected memory leaks!
Dumping objects ->
{209} normal block at 0x005E9C68, 20 bytes long.
Data: <h ^ h ^ h ^ > 68 9C 5E 00 68 9C 5E 00 68 9C 5E 00 CD CD CD CD
{208} normal block at 0x005E9C20, 8 bytes long.
Data: < ; > F8 FE 3B 00 00 00 00 00
Object dump complete.
Here is the solution to this: Just enclose the definition in braces like this:
int _tmain(int argc, _TCHAR* argv[])
{
printf("I'm not leaking any more\n");
{
std::set<int> s;
}
_CrtDumpMemoryLeaks();
return 0;
}
It’s a strange behavior and I’m wondering if this is a Bug in Microsoft Compilers or some STL-Problem? I guess it’s the former. If maybe anyone tried this on a Linux-System, it would be interesting to know…
How is the first example a leak?
sis still in scope, so of course it still has memory associated with it. You’d have to make your memory leak detection call after_tmainreturns to get a valid answer.In your second example,
sis out of scope and has been destroyed, so it’s no surprise that it has no more memory associated with it.You just need to call the leak checker at spots in your code that make sense.