C++提供强大灵活性和方便性,但是与之而来的是指针和内存一不小心就出问题,针对常见的内存泄露和溢出微软提供了crtdbg库来帮助检查,这里封装了crtdbg库的内容让你轻轻松松使用这些检测功能。

使用示例

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{

    //初始化,开始检查,开启自动检查泄露,不自动检查溢出,不弹框提醒,日志输出到文件log.txt中
    InitMemoryCheck(true, false, false, _T("c:\\log.txt"));

    //内存泄露检查
    int* a = new int[20];
    char* b = (char*)malloc(10);
    //MemCheckLeak();

    //内存溢出检查
    a[20] = 1;
    MemCheckOverflow();
    printf("\n");

    //堆内存状态比较
    MemStateSave();
    int* c = (int*)malloc(10);
    int* d = new int[10];
    MemStateSave();
    MemStateCompareDump();
    char* e = new char[1];
    MemStateSave();
    MemStateCompareDump();

    //自定义报告输出,可做日志用
    MemReportError("错误-自定义报告输出\n");
    MemReportWarn("警告-自定义报告输出\n");
    MemReportAssert("断言-自定义报告输出\n");
    printf("\n");

    //检查完毕
    UninitMemoryCheck();
    return 0;

    /**程序结束时自动检查泄露**/
}

输出如下

HEAP CORRUPTION DETECTED: after Client block (#123) at 0x00859C90.
CRT detected that the application wrote to memory after end of heap buffer.

Memory allocated at e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(10).
Client located at 0x00859C90 is 80 bytes long.

Memory allocated at e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(10).
0 bytes in 0 Free Blocks.
10 bytes in 1 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
40 bytes in 1 Client Blocks.
Largest number used: 0 bytes.
Total allocations: 50 bytes.
0 bytes in 0 Free Blocks.
0 bytes in 0 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
1 bytes in 1 Client Blocks.
Largest number used: 0 bytes.
Total allocations: 1 bytes.
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(30) : 错误-自定义报告输出
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(31) : 警告-自定义报告输出
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(32) : Assertion failed: 断言-自定义报告输出

Detected memory leaks!
Dumping objects ->
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(25) : {128} client block at 0x00859E18, subtype 0, 1 bytes long.
 Data: < > CD 
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(22) : {127} client block at 0x00859DB0, subtype 0, 40 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(21) : {126} normal block at 0x00859D68, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD 
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(11) : {124} normal block at 0x00859D20, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD 
e:\code\test\内存泄漏和溢出检测\leaktest\main.cpp(10) : {123} client block at 0x00859C90, subtype 0, 80 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
Object dump complete.

下载

源代码下载链接