VS中自带了内存泄露检测工具,若要启用内存泄露检测,则在程序中包括以下语句:
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
它们的先后顺序不能改变。通过包括 crtdbg.h,将malloc和free函数映射到其”Debug”版本_malloc_dbg和_free_dbg,这些函数将跟踪内存分配和释放。此映射只在调试版本(在其中定义了_DEBUG)中发生。#define语句将CRT堆函数的基版本映射到对应的”Debug”版本。
测试代码如下:
#include <iostream>
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define new DEBUG_CLIENTBLOCK
#endif
void test_c()
{
int* p = (int*)malloc(10 * sizeof(int));
//free(p);
}
void test_cpp()
{
int* p = new int[10];
//delete [] p;
}
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);//_CrtDumpMemoryLeaks();
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
test_c();
test_cpp();
std::cout << "ok" << std::endl;
}
结果图如下:


本文介绍了Visual Studio中如何启用内存泄露检测功能,通过引入特定宏和头文件,实现malloc和free函数的映射,从而追踪内存分配和释放情况。演示了测试代码的配置和执行流程,并展示了内存泄漏检测的结果。
221

被折叠的 条评论
为什么被折叠?



