Does the string cause a memory leak?

Visual C ++ detected memory leaks in my code, so I reduced it to the simplest test case as I could, and got the following:

#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 on "string foo;" he discovers nothing.

Do I have to somehow free foo?

+4
source share
3 answers

You run _CrtDumpMemoryLeaks() too early and tell the body string as a leak. Run it only after all local objects can be destroyed.

Or complete all significant work in a separate function

 void doStuff() { string variable; } 

or add a nested area:

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

You must call _CrtDumpMemoryLeaks after the program / block is completed. The best way to do this is to have CRT invoke this when the program terminates, as indicated in _ article CrtDumpMemoryLeaks msdn :

_CrtDumpMemoryLeaks is often 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 the end of the program by turning on the bit_CRTDBG_LEAK_CHECK_DF bit field flag _crtDbgFlag using the function _CrtSetDbgFlag.

Calling it the way you did it, it detects foo as a leak, because its destructor has not yet been called, since the execution block has not ended yet.

+9
source

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

Try the following:

 #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; } 
+2
source

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


All Articles