通过define _CRTDBG_MAP_ALLOC宏来检测windows上的code是否有内存泄露

来源:互联网 发布:免费买东西软件 编辑:程序博客网 时间:2024/05/23 10:58

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#endifvoid 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;}
结果图如下:


GitHub:https://github.com/fengbingchun/Messy_Test

0 0