使用 Visual Studio 在 C++ 应用程序中查找内存泄漏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4790564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding memory leaks in a C++ application with Visual Studio
提问by devnull
In Linux, I have been using valgrind for checking if there are memory leaks in an application. What is the equivalent in Windows? Can this be done with Visual Studio 2010?
在 Linux 中,我一直使用 valgrind 来检查应用程序中是否存在内存泄漏。Windows 中的等价物是什么?这可以用 Visual Studio 2010 完成吗?
回答by Default
How about Visual Leak Detector? It's not inbuild, but I do think it's the most popular one.
视觉检漏仪怎么样?它不是内置的,但我认为它是最受欢迎的。
回答by Malick
Visual Studio 2019 has a decent memory analysis tool, it may be used interactively while debugging or by programming (without debugging), I show a minimal example in both cases in the following.
Visual Studio 2019 有一个不错的内存分析工具,它可以在调试时交互使用或通过编程(不调试)使用,我在下面的两种情况下都展示了一个最小的例子。
The main idea is to take a snapshot of the heap at the beginning and at the end of the process, then to compare the states of memory to detect potential memory leaks.
主要思想是在进程开始和结束时对堆进行快照,然后比较内存状态以检测潜在的内存泄漏。
Interactively
交互式
Create the following main.cpp
file (in a new console application) :
创建以下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 :
然后 :
- Put a breakpoint on the first line "int a..."
- Click Debug > Windows > Show Diagnostic Tools; and pick memory usage
- 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. - Click on the red arrow in the second snapshot (in memory usage tab)
- this will open a new "snapshot" tab that permits you to compare this snapshot with the first one (or another one) and to detect memory leaks. In this example there is a memory leak for variable
s
(stackoverflow_pb). You can find it by double click the "char[]" object.
- 在第一行“int a...”上放置一个断点
- 单击调试 > Windows > 显示诊断工具;并选择内存使用情况
- 然后调试代码(F5),当断点被命中时,点击
Take snapshot
Memory Usage summary 工具栏。 - 转到最后一行“返回0 ..”( (
step over
)F10数次)和另一个快照。 - 单击第二个快照中的红色箭头(在内存使用选项卡中)
- 这将打开一个新的“快照”选项卡,允许您将此快照与第一个(或另一个)进行比较并检测内存泄漏。在此示例中,变量
s
(stackoverflow_pb)存在内存泄漏 。您可以通过双击“char[]”对象找到它。
The key steps of the above procedure are shown in the following image:
上述过程的关键步骤如下图所示:
By programming
通过编程
Replace the code with the following:
将代码替换为以下内容:
#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 snapchot
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 snapchot
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;
}
It does the same thing but by code, so you can integrate it in an automatic build system, the functions _CrtMemCheckpoint
take the snapshots and _CrtMemDifference
compare the memory states of snapshot and returns true is they are different.
它做同样的事情,但通过代码,所以你可以将它集成到一个自动构建系统中,这些函数_CrtMemCheckpoint
获取快照并_CrtMemDifference
比较快照的内存状态,如果它们不同,则返回 true。
Since it is the case, it enters the conditional block and prints details about the leaks via several functions (see _CrtMemDumpStatistics, _CrtMemDumpAllObjectsSinceand _CrtDumpMemoryLeaks- the latter doesn't require snapshots).
既然如此,它就会进入条件块并通过几个函数打印有关泄漏的详细信息(请参阅_CrtMemDumpStatistics、_CrtMemDumpAllObjectsSince和_CrtDumpMemoryLeaks- 后者不需要快照)。
To see the output, put a break point in the last line "return 0", hit F5
and look at the debug console. Here is the output :
要查看输出,请在最后一行“return 0”中放置一个断点,点击F5
并查看调试控制台。这是输出:
To get more information, see the following links :
要获取更多信息,请参阅以下链接:
- Interactive analysis : Measure memory usage in Visual Studio
- via programming : Find memory leaks with the CRT libraryand CRT debug Heap Files(for heap corruption also)
- 交互式分析:在 Visual Studio 中测量内存使用情况
- 通过编程:使用 CRT 库和CRT 调试堆文件查找内存泄漏(也用于堆损坏)
回答by AntonK
Dr. Memoryis a memory monitoring tool capable of identifying memory-related programming errors such as accesses of uninitialized memory, accesses to unaddressable memory (including outside of allocated heap units and heap underflow and overflow), accesses to freed memory, double frees, memory leaks, and (on Windows) handle leaks, GDI API usage errors, and accesses to un-reserved thread local storage slots.
Dr. Memory是一种内存监控工具,能够识别与内存相关的编程错误,例如访问未初始化内存、访问不可寻址内存(包括分配的堆单元之外和堆下溢和溢出)、访问已释放内存、双重释放、内存泄漏,以及(在 Windows 上)处理泄漏、GDI API 使用错误以及对未保留线程本地存储槽的访问。
Dr. Memory operates on unmodified application binaries running on Windows, Linux, Mac, or Android on commodity IA-32, AMD64, and ARM hardware.
Dr. Memory 可在商用 IA-32、AMD64 和 ARM 硬件上运行在 Windows、Linux、Mac 或 Android 上的未修改应用程序二进制文件上运行。
Dr. Memory is built on the DynamoRIOdynamic instrumentation tool platform.
Dr. Memory 建立在DynamoRIO动态仪器工具平台之上。
回答by Stephen Kellett
C++ Memory Validatorfinds memory and handle leaks in native Windows programs built with Visual Studio, Delphi and other compilers. Fast and can handle large workloads (some users track several billion allocations and deallocations in one run).
C++ 内存验证器在使用 Visual Studio、Delphi 和其他编译器构建的本机 Windows 程序中查找内存并处理泄漏。快速并且可以处理大量工作负载(一些用户在一次运行中跟踪数十亿次分配和解除分配)。
Disclosure: I'm the designer of C++ Memory Validator. We built it because other tools couldn't handle the workload when we were working with SolidWorks R&D Ltd.
披露:我是 C++ Memory Validator 的设计者。我们构建它是因为当我们与 SolidWorks R&D Ltd 合作时,其他工具无法处理工作量。
回答by Oleg Smirnov
Visual Studio 2015 and later versions have Native Memory Leak Diagnostic Tool, check this for details: https://dzone.com/articles/native-memory-leak-diagnostics.
Visual Studio 2015 及更高版本具有 Native Memory Leak Diagnostic Tool,详情请查看:https: //dzone.com/articles/native-memory-leak-diagnostics。
回答by ckv
You can use DevPartner tool for finding memory leaks in C++ applications using visual studio.
您可以使用 DevPartner 工具使用 Visual Studio 查找 C++ 应用程序中的内存泄漏。
回答by nkvns
Application Verifieris good tool for detecting leaks in native (c or c++) application. You can use it along with Visual studio or Windbg. Aaprt from memory leaks, you can check for heap corruptions, invalid handle usage as well. Using application verifier along with windbg (!analyze -v) provides good insights.
Application Verifier是检测原生(c 或 c++)应用程序泄漏的好工具。您可以将它与 Visual Studio 或 Windbg 一起使用。Aaprt 从内存泄漏,您可以检查堆损坏,无效句柄使用以及。将应用程序验证程序与 windbg (!analyze -v) 一起使用可提供很好的见解。