Is there a way to show memory leaks report in a C++ application using Visual Studio Code?
Perhaps a certain library? An extension? Using MinGW compiler?
I'm using Visual Studio Code (1.41.1) on Windows 10 with C++ extension (0.26.3). I've configured VS Code with MSVC compiler toolset (2019) as written in Configure VS Code for Microsoft C++. However I'm unable to show memory leaks using the CRT library, as written in Find memory leaks with the CRT library. My simple example code:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
int main() {
printf("Hello world!\n");
int *a = new int;
*a = 8;
//delete a;
_CrtDumpMemoryLeaks();
return 0;
}
Using this code I cannot see any report generated by _CrtDumpMemoryLeaks()
.
When debugging the code it seems that the compiler skips the line _CrtDumpMemoryLeaks();
entirely.
Am I doing something wrong?
I've tried changing the configurations with _DEBUG=1
define, however the compiler even skips a #ifdef _DEBUG
statement.
The best approach to checking for the existence of a memory leak in your application is by looking at your RAM usage and investigating the total amount of memory been used versus the total amount available. Evidently, it is advisable to obtain snapshots of your memory's heap dump while in a production environment.
With Java VisualVM, we can memory-monitor the Java Heap and identify if its behavior is indicative of a memory leak. After just 30 seconds, the Old Generation is almost full, indicating that, even with a Full GC, the Old Generation is ever-growing, a clear sign of a memory leak.
In this article, you can learn how to find memory leaks in C and C++ applications with the help of a runtime error detection tool.
It seems that you can find memory leaks in VS Code C++ application with MSVC by simply adding the compiler option "/MDd"
or "/MTd"
in the args
array of the tasks.json
file within the project's .vscode
folder (without any 3rd party application or tool).
Something like this:
"args": [
"/Zi", // Generates complete debugging information
"/MDd", // Use /MDd or /MTd to define _DEBUG and allow _CrtDumpMemoryLeaks()
"/EHsc", // Specifies the model of exception handling - mode 'sc'
"/Fe:", // Renames the executable file
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"${file}"
],
This basically enables everything listed in Find memory leaks with the CRT library
Then, when running the program, _CrtDumpMemoryLeaks()
detects the memory leaks and shows them within the DEBUG CONSOLE
:
Detected memory leaks!
Dumping objects ->
{113} normal block at 0x015C8460, 4 bytes long.
Data: < > 08 00 00 00
Object dump complete.
Finally, you can enter the number within the curly brackets into the _CrtSetBreakAlloc(113)
command to create a memory-allocation breakpoint to find which variable you forgot to delete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With