C++中基于Crt的内存泄露检测

发表于:2013-3-06 09:15

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Richard Wei    来源:51Testing软件测试网采编

  尽管这个概念已经让人说滥了 ,还是想简单记录一下, 以备以后查询。

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif


int _tmain(int argc, _TCHAR* argv[])
{
    char* p = new char();
    char* pp = new char[10];
    char* ppp = (char*)malloc(10);

    _CrtDumpMemoryLeaks();

    return 0;
}

  主要原理是运用Crt 的内存调试功能,通过宏替代默认的operator new,让它被下面版本替代:

void *__CRTDECL operator new(
        size_t cb,
        int nBlockUse,
        const char * szFileName,
        int nLine
        )
        _THROW1(_STD bad_alloc)
{
    /* _nh_malloc_dbg already calls _heap_alloc_dbg in a loop and calls _callnewh
       if the allocation fails. If _callnewh returns (very likely because no
       new handlers have been installed by the user), _nh_malloc_dbg returns NULL.
     */
    void *res = _nh_malloc_dbg( cb, 1, nBlockUse, szFileName, nLine );

    RTCCALLBACK(_RTC_Allocate_hook, (res, cb, 0));

    /* if the allocation fails, we throw std::bad_alloc */
    if (res == 0)
    {
        static const std::bad_alloc nomem;
        _RAISE(nomem);
    }

    return res;
}

  这样Crt会把此次分配内存的文件名和行号以及大小等记录下来,最后当调用用_CrtDumpMemoryLeaks();时如果还没释放就会打印出来。

  结果如下:

Detected memory leaks!
Dumping objects ->
f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(23) : {108} normal block at 0x0003A1A8, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD
f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(22) : {107} client block at 0x0003A160, subtype 0, 10 bytes long.
 Data: <          > CD CD CD CD CD CD CD CD CD CD
f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(21) : {106} client block at 0x0003A120, subtype 0, 1 bytes long.
 Data: < > 00
Object dump complete.

41/41234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号