首页 > 解决方案 > 使用 VS Code 在 C++ 应用程序中查找内存泄漏

问题描述

有没有办法使用 Visual Studio Code 在 C++ 应用程序中显示内存泄漏报告?

也许某个图书馆?一个扩展?使用 MinGW 编译器?

我在带有 C++ 扩展 (0.26.3) 的 Windows 10 上使用 Visual Studio Code (1.41.1)。我已经使用 MSVC 编译器工具集 (2019) 配置了 VS Code,如Configure VS Code for Microsoft C++中所述。但是,我无法使用 CRT 库显示内存泄漏,如Find memory leaks with the CRT library 中所述。我的简单示例代码:

#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;
}

使用此代码,我看不到任何由_CrtDumpMemoryLeaks(). 在调试代码时,编译器似乎_CrtDumpMemoryLeaks();完全跳过了这一行。难道我做错了什么?我试过用_DEBUG=1define改变配置,但是编译器甚至跳过了一条#ifdef _DEBUG语句。

标签: c++visual-c++visual-studio-codememory-leaksvscode-debugger

解决方案


似乎您可以通过简单地添加编译器选项"/MDd""/MTd"在项目文件夹args中的文件数组中(没有任何第三方应用程序或工具),在带有 MSVC 的 VS Code C++ 应用程序中找到内存泄漏。像这样的东西:tasks.json.vscode

"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}"
        ],

这基本上启用了使用 CRT 库查找内存泄漏中列出的所有内容。 然后,在运行程序时,_CrtDumpMemoryLeaks()检测内存泄漏并将它们显示在DEBUG CONSOLE

Detected memory leaks!
Dumping objects ->
{113} normal block at 0x015C8460, 4 bytes long.
 Data: <    > 08 00 00 00 
Object dump complete.

最后,您可以在命令中输入大括号内的数字_CrtSetBreakAlloc(113)以创建内存分配断点,以查找您忘记删除的变量。


推荐阅读