Memory Leaks in Visual Studio

I have a memory leak with this simple code using std :: thread in 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 on the first two lines of the main method, I have no memory leaks.

Where is he from?

EDIT: The leak is still here with this code:

 #include <thread> void f(){} int main(){ { std::thread t(f); t.join(); } _CrtDumpMemoryLeaks(); return 0;} 
+4
source share
4 answers

CrtDumpMemoryLeaks is notoriously unreliable. It is possible that the standard library intentionally leaks a one-time allocation when using std :: thread for the first time. To find out if there is a real memory leak, try the following:

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

And then see if the size of the leak increases with increasing LIMIT. If it is not, you are fine.

+9
source

When resetting leaks, the flow destructor is not yet running. You must try:

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

Probably because the thread object allocates some data, and since the destructor did not start when the memory was unloaded, which it considered a leak.

Try to put a stream object, create and join a separate function.

0
source

You should not call CrtDumpMemoryLeaks in this place - or if you accept pseudo-leaks.

Static object destructors are not yet running, and such objects may be in memory. If you use MFC, it will trigger a leak dump from the dtor of the AFX_STATE object, which is not late enough to see only real leaks.

In the meantime, you can use _ crtBreakAlloc to find out where this block is allocated, I'm sure the call stack will lead you to some local static function in the RTL territory, and you can even set a breakpoint on your dtor to see that it actually frees up memory a bit after your dump.

0
source

Source: https://habr.com/ru/post/1482355/


All Articles