Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string causes a memory leak?

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?

like image 734
carbin Avatar asked Nov 28 '22 10:11

carbin


2 Answers

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.

like image 30
Shinnok Avatar answered Dec 07 '22 22:12

Shinnok


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;
}
like image 109
sharptooth Avatar answered Dec 07 '22 23:12

sharptooth