12

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.

Oren
  • 161
  • 1
  • 1
  • 7

1 Answers1

4

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.

Oren
  • 161
  • 1
  • 1
  • 7
  • this was working for me a few days ago. Today I come back and the program is just skipping over that call to _CrtDumpMemoryLeaks any idea why? – Daniel Williams Mar 17 '22 at 03:12