简体   繁体   中英

Memory Leaks in Visual Studio

I have a memory leaks with this simple code using std::thread on Visual Studio Pro 2012:

#include <thread>

void f(){}

int main(){
    std::thread t(f);
    t.join();
    _CrtDumpMemoryLeaks();
    return 0;}

Win32 Output:

Detected memory leaks!
Dumping objects ->
{293} normal block at 0x00A89520, 44 bytes long.
 Data: <                > 01 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 
Object dump complete.

x64 Output:

Detected memory leaks!
Dumping objects ->
{293} normal block at 0x00000000003FCB00, 72 bytes long.
 Data: <                > 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
Object dump complete.

If I comment the two first lines of the main method, I have no memory leaks.

Where does it come from ?

EDIT: The leak is still here with that code:

#include <thread>

void f(){}

int main(){
    {
        std::thread t(f);
        t.join();
    }
    _CrtDumpMemoryLeaks();
    return 0;}

CrtDumpMemoryLeaks is notoriously unreliable. It may well be that the standard library intentionally leaks a one-time allocation when you first use std::thread. To find out if there's a real memory leak, try this:

for (int i = 0; i < LIMIT; ++i) {
  std::thread t(f); t.join();
}
_CrtDumpMemoryLeaks();

And then see if the leak size increases as you increase LIMIT. If it doesn't, you're fine.

When you dump the leaks the thread destructor has not yet run. You should try:

int main()
{
  {
    std::thread t(f);
    t.join();
  }
  _CrtDumpMemoryLeaks();
  return 0;
}

Probably because the thread object allocates some data, and as the destructor hasn't run when you dump the memory it's counted as a leak.

Try putting the thread object, creation and join in a separate function.

You're not supposed to call CrtDumpMemoryLeaks at that spot -- or if you do accept pseudo-leaks.

The destructors of static objects did not yet run, and such objects can sit on memory. If you use MFC it will run leak dump from dtor of AFX_STATE object that is notmally late enough to see only real leaks.

In the meantime you can use _crtBreakAlloc to see where that block is allocated, I bet the call stack will lead you to some function-local static in the RTL territory and you can even set a breakpoint on its dtor to see it actually releases the memory a little after your dump.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM