Visual Studio 2019 有一个不错的内存分析工具,它可以在调试或编程时以交互方式使用(无需调试),我在下面的两种情况下都展示了一个最小的示例。
主要思想是在进程开始和结束时拍摄堆快照,然后比较内存状态以检测潜在的内存泄漏。
互动式
创建以下内容main.cpp
文件(在新的控制台应用程序中):
#include <string.h>
int main()
{
int a = 1;
char* s = new char[17];
strcpy_s(s,17,"stackoverflow_pb");
char* ss = new char[14];
strcpy_s(ss, 14,"stackoverflow");
delete[] ss;
return 0;
}
Then :
- 在第一行“int a...”上放置一个断点
- 单击“调试”>“Windows”>“显示诊断工具”;并选择内存使用情况
- Then debug the code (F5), when the breakpoint is hit, click
Take snapshot
on the Memory Usage summary toolbar.
- Go to the last line "return 0.." (
step over
(F10) several times) and take another snapshot.
- 单击第二个快照中的红色箭头(在“内存使用情况”选项卡中)
- 这将打开一个新的“快照”选项卡,允许您将此快照与第一个(或另一个)快照进行比较并检测内存泄漏。在此示例中,变量存在内存泄漏
s
(stackoverflow_pb)。您可以通过双击“char[]”对象找到它。
上述过程的关键步骤如下图所示:
通过编程
将代码替换为以下内容:
#include <iostream>
#include "windows.h"
#define _CRTDBG_MAP_ALLOC //to get more details
#include <stdlib.h>
#include <crtdbg.h> //for malloc and free
int main()
{
_CrtMemState sOld;
_CrtMemState sNew;
_CrtMemState sDiff;
_CrtMemCheckpoint(&sOld); //take a snapshot
char* s = new char[17];
strcpy_s(s, 17, "stackoverflow_pb");
char* ss = new char[14];
strcpy_s(ss, 14, "stackoverflow");
delete[] ss;
_CrtMemCheckpoint(&sNew); //take a snapshot
if (_CrtMemDifference(&sDiff, &sOld, &sNew)) // if there is a difference
{
OutputDebugString(L"-----------_CrtMemDumpStatistics ---------");
_CrtMemDumpStatistics(&sDiff);
OutputDebugString(L"-----------_CrtMemDumpAllObjectsSince ---------");
_CrtMemDumpAllObjectsSince(&sOld);
OutputDebugString(L"-----------_CrtDumpMemoryLeaks ---------");
_CrtDumpMemoryLeaks();
}
return 0;
}
它做同样的事情,但是通过代码,所以你可以将它集成到自动构建系统中,功能_CrtMemCheckpoint https://learn.microsoft.com/cpp/c-runtime-library/reference/crtmemcheckpoint?view=vs-2019拍摄快照并_CrtMemDifference https://learn.microsoft.com/cpp/c-runtime-library/reference/crtmemdifference?view=vs-2019比较快照的内存状态,如果不同则返回 true。
既然是这种情况,它就会进入条件块并通过几个函数打印有关泄漏的详细信息(请参阅_CrtMemDumpStatistics https://learn.microsoft.com/cpp/c-runtime-library/reference/crtmemdumpstatistics?view=vs-2019 , _CrtMemDumpAllObjectsSince https://learn.microsoft.com/cpp/c-runtime-library/reference/crtmemdumpallobjectssince?view=vs-2019 and _CrtDump内存泄漏 https://learn.microsoft.com/cpp/c-runtime-library/reference/crtdumpmemoryleaks?view=msvc-160- 后者不需要快照)。
要查看输出,请在最后一行“return 0”中放置一个断点,点击F5
并查看调试控制台。这是输出:
要获取更多信息,请参阅以下链接:
- 互动分析:在 Visual Studio 中测量内存使用情况 https://learn.microsoft.com/visualstudio/profiling/memory-usage?view=vs-2019
- 通过编程: and CRT 调试堆文件 https://learn.microsoft.com/visualstudio/debugger/crt-debug-heap-details?view=vs-2019(也适用于堆损坏)