在vs中通过函数检测是否内存泄漏
1. 判断方法
在程序vs编写代码,在想要追踪的方法结尾,使用_CrtDumpMemoryLeaks()函数可以检测是否内存泄漏。推荐在main函数结尾使用,追踪范围更大。
#include <iostream>
int main()
{
char* c1 = (char*)malloc(15);
delete c1;
char* c = (char*)malloc(15);
char* c3 = (char*)malloc(15);
_CrtDumpMemoryLeaks();
}
通过f5调试执行完成后,在输出窗口,注意是输出窗口,不是控制台窗口,看到如下提示就表示有内存泄漏了。
Detected memory leaks!
Dumping objects ->
{153} normal block at 0x00F04D68, 15 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
{152} normal block at 0x00F092F0, 15 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
2. 上述内容涵义(从第三行开始看起)
内存分配编号(在大括号内)。
块类型(普通、客户端或 CRT)。
十六进制形式的内存位置。
以字节为单位的块大小。
前 16 字节的内容(亦为十六进制)
3. 如何定位哪里内存泄漏?
3.1 通过_CrtSetBreakAlloc()函数,把内存分配编号作为参数,就会在f5执行时停止在问题位置。
#include <iostream>
int main()
{
_CrtSetBreakAlloc(152);
_CrtSetBreakAlloc(153);
char* c1 = (char*)malloc(15);
delete c1;
char* c = (char*)malloc(15);
char* c3 = (char*)malloc(15);
_CrtDumpMemoryLeaks();
}
3.2 通过_CrtSetDbgFlag()函数定位文件和位置
#include <iostream>
#define new new(_CLIENT_BLOCK, __FILE__, __LINE__)
int main()
{
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
int* p = new int;
_CrtDumpMemoryLeaks();
}
看到类似如下内容
Detected memory leaks!
Dumping objects ->
C:\Users\12250\source\repos\OnlyForTest\OnlyForTest2\main.cpp(17) : {151} client block at 0x00B7C270, subtype 0, 4 bytes long.
Data: < > CD CD CD CD
Object dump complete.
就表示是在我的解决方案“OnlyForTest”下的项目“OnlyForTest2”下的main.cpp文件第17行产生内存泄漏了。
最后, 觉得文章对你有用的话,给个下面的三连(点赞,收藏,打赏)吧!