4
votes

Visual C++ found memory leaks in my code so I whittled it down to as simplest test case as I could and got this:

#define _CRTDBG_MAP_ALLOC   // required
#include <stdlib.h>         // to enable MSVC++
#include <crtdbg.h>         // memory leak detection

#include <string>

using namespace std;

int main() {

    string foo;

    _CrtDumpMemoryLeaks();

    return 0;
}

Output:

Detected memory leaks!
Dumping objects ->
{130} normal block at 0x008748A8, 8 bytes long.
 Data:  B4 F9 44 00 00 00 00 00 
Object dump complete.

If I comment out "string foo;" it doesn't detect anything.

Should I be deallocating foo somehow?

3

3 Answers

12
votes

You're running _CrtDumpMemoryLeaks() too early and it reports the string body as a leak. Only run it after all the local objects could have been destroyed.

Either wrap all meaningful work in a separate function

void  doStuff()
{
    string variable;
}

or add nested scope:

int main()
{
    {
       string variable;
    }
    _CrtDumpMemoryLeaks();
    return 0;
}
10
votes

You should call _CrtDumpMemoryLeaks after program/block termination. The best way to do that is have CRT call that itself upon program termination, as stated in the _CrtDumpMemoryLeaks msdn article:

_CrtDumpMemoryLeaks is frequently called at the end of program execution to verify that all memory allocated by the application has been freed. The function can be called automatically at program termination by turning on the _CRTDBG_LEAK_CHECK_DF bit field of the _crtDbgFlag flag using the _CrtSetDbgFlag function.

By calling it the way you did, it will detect the foo as a leak since it's destructor hasn't yet been called since the execution block hasn't ended yet.

2
votes

You are calling _CrtDumpMemoryLeaks(); while the string still exists - of course it detects that the string still exists!

Try this:

#define _CRTDBG_MAP_ALLOC   // required
#include <stdlib.h>         // to enable MSVC++
#include <crtdbg.h>         // memory leak detection

#include <string>

using namespace std;

int main() {
    {    
      string foo;
    }

    _CrtDumpMemoryLeaks();

    return 0;
}