1. 程式人生 > >VS:define_CRTDBG_MAP_ALLOC巨集檢測windows上的code是否有記憶體洩露

VS:define_CRTDBG_MAP_ALLOC巨集檢測windows上的code是否有記憶體洩露

VS中自帶記憶體洩露檢測工具,若要啟用記憶體洩露檢測,則在程式中新增以下語句:

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); 

【注】:它們的先後順序不能改變。

通過包括 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;
}

參考文獻:

1. https://blog.csdn.net/fengbingchun/article/details/51114925