c++ - 使用 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=1
define改变配置,但是编译器甚至跳过了一条#ifdef _DEBUG
语句。
解决方案
似乎您可以通过简单地添加编译器选项"/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)
以创建内存分配断点,以查找您忘记删除的变量。
推荐阅读
- angular - NGRX - 如何通过reducer更新数组中对象中的字段?
- java - 如何从给定季度获取月份
- python - 如何在 python 中读取 .img 文件?
- graph - 证明存在一个顶点的最小生成树总是包含该顶点的最短边
- json - 根据子对象数组中的值进行选择
- gekko - GEKKO 是否支持离散整数空间问题的任何无梯度方法?
- ios - UINavigationController 在更改高度时会切断内容吗?(gif)
- reactjs - npm start 和在 react 中编译的问题
- sql - 使用两个表给出一个输出
- reactjs - $("
") React Native 中的等价物