内存泄露检测工具

一 VisualC++ debugger 和 CRT 库

  • 第一步: 包含以下头文件
#define _CRTDBG_MAP_ALLOC 
#include <stdlib.h> 
#include <crtdbg.h>
  • 第二步: 接管 new 操作符
#ifdef _DEBUG 
#ifndef DBG_NEW 
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ ,__LINE__) 
#define new DBG_NEW 
#endif 
#endif
  • 第三步: 在代码结束出输出内存泄漏信息
_CrtDumpMemoryLeaks();

示例:

#define _CRTDBG_MAP_ALLOC 
#include <stdlib.h> 
#include <crtdbg.h>

#ifdef _DEBUG 
#ifndef DBG_NEW 
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ ,__LINE__) 
#define new DBG_NEW 
#endif 
#endif

int main()
{

    int* p = new int[100];
    p[0] = 0;
    int* p1 = new int[100];
    p1[0] = 0;

    _CrtDumpMemoryLeaks();
    return 0;
}

调试的时候就可以看到有内存泄露
image

二 内存泄露工具

Windows : Purify,BoundsCheaker、Deleaker、VisualLeak Detector(VLD)
Linux 平台: Valgrind memcheck

posted @ 2022-04-21 08:01  荒年、  阅读(91)  评论(0编辑  收藏  举报