Windows调试之内存泄漏

查找内存泄漏的重要性我想就不必多说了,言归正传!

发生内存泄漏的简单c++程序

#include <iostream>
using namespace std;

int main()
{
    cout << "Enter" << endl;
    const int BUFER_SIZE = 10;
    char *pLeakBufByMalloc = static_cast<char*>(malloc(BUFER_SIZE));    
    char *pLeakBufByNew = new char[BUFER_SIZE];
    cout << "Leave" << endl;
    //free(pLeakBufByMalloc);
    //delete[] pLeakBufByNew;
    return 0;
}

默认情况下是不激活内存泄漏检查功能的,需要包含

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

_CRTDBG_MAP_ALLOC 宏需要先于包含crtdbg.h文件定义,这样后续malloc 和free 函数的调用就替换成 _malloc_dbg 和 _free_dbg了,这俩个函数能够跟踪内存的申请和释放操作,
简言之就是,当我们malloc N字节大小的内存的时候,dbg版本的会malloc更多的内存统计信息,比如大小,文件位置__FILE__ __LINE__ 等等。

一般在程序结尾通过调用 _CrtDumpMemoryLeaks() 来打印crt 内存堆泄漏情况。
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
using namespace std;
int main()
{
    cout << "Enter" << endl;
    const int BUFER_SIZE = 10;
    char *pLeakBufByMalloc = static_cast<char*>(malloc(BUFER_SIZE));    
    char *pLeakBufByNew = new char[BUFER_SIZE];
    cout << "Leave" << endl;
    //free(pLeakBufByMalloc);
    //delete[] pLeakBufByNew;
    _CrtDumpMemoryLeaks();//仅在DEBUG下生效,否认忽略
    return 0;
}
运行结果就能看到:
Detected memory leaks!
Dumping objects ->
{130} normal block at 0x003B6BA0, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD
....\debugskills\main.cpp(11) : {129} normal block at 0x003B6B58, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD
Object dump complete.


有没有发现 通过new 运算符申请的内存没有输出代码位置信息,没有这个信息的话,那我们在成千上万行代码中定位内存泄漏就会很麻烦

其实,很简单,只要我们在DEBUG 模式下把new 重新define一下就好了

#define DEBUG_CLIENTBLOCK   new( _CLIENT_BLOCK, __FILE__, __LINE__)
#define new DEBUG_CLIENTBLOCK

这样就OK了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值