1

我编写了一些实用程序代码来检测程序关闭时的内存泄漏。detect_leaks.hpp 和 cpp 包含设置功能,在程序中您只需在程序启动时调用 start_detecting() 函数。

请注意,此代码使用 Microsoft 调试功能,因此仅适用于 Windows。

我的报告打印出文件中带有泄漏分配的新行,因为我有这个:

#define new new(_CLIENT_BLOCK,__FILE__, __LINE__)

但是我如何为 malloc 做同样的事情呢?或者,如果需要,我不介意将名称更改为例如 mmalloc。是的,我知道我不应该使用 malloc,但我有一些非常旧的代码。

这是到目前为止的代码:

检测泄漏.hpp:

#ifndef __DETECT_LEAKS_HPP__
#define __DETECT_LEAKS_HPP__

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <crtdbg.h>

#define new new(_CLIENT_BLOCK,__FILE__, __LINE__)

// The following macros set and clear, respectively, given bits
// of the C runtime library debug flag, as specified by a bitmask.
#ifdef   _DEBUG
#define  SET_CRT_DEBUG_FIELD(a) \
    _CrtSetDbgFlag((a) | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG))
#define  CLEAR_CRT_DEBUG_FIELD(a) \
    _CrtSetDbgFlag(~(a) & _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG))
#else
#define  SET_CRT_DEBUG_FIELD(a)   ((void) 0)
#define  CLEAR_CRT_DEBUG_FIELD(a) ((void) 0)
#endif

void start_detecting();

#endif // __DETECT_LEAKS_HPP__

检测泄漏.cpp:

#include "detect_leaks.hpp"

void start_detecting() {
    // Send all reports to STDOUT
    _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
    _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
    _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
    _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
    _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
    _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );

    // Set the debug-heap flag so that freed blocks are kept on the
    // linked list, to catch any inadvertent use of freed memory
    SET_CRT_DEBUG_FIELD( _CRTDBG_DELAY_FREE_MEM_DF );

    // Set the debug-heap flag so that memory leaks are reported when the process terminates.
    SET_CRT_DEBUG_FIELD( _CRTDBG_LEAK_CHECK_DF );
}

main.cpp(示例用法):

#include "detect_leaks.hpp"

int  main()
{
    start_detecting();

    char* s = (char*)malloc(100);
    strcpy(s, "ABC leak1");

    char* s1 = new char[100]();
    strcpy(s1, "ABC leak2");

    return 0;
}

样本打印输出:

Detected memory leaks!
Dumping objects ->
\memleak_malloc\main.cpp(10) : {74} client block at 0x00161A90, subtype 0, 100 bytes long.
 Data: <ABC leak2       > 41 42 43 20 6C 65 61 6B 32 00 00 00 00 00 00 00
{73} normal block at 0x00164F50, 100 bytes long.
 Data: <ABC leak1       > 41 42 43 20 6C 65 61 6B 31 00 CD CD CD CD CD CD
Object dump complete.
4

1 回答 1

2

抱歉问了。我从另一个 SO question 中找到了答案。

挺方便的,只要

#define _CRTDBG_MAP_ALLOC

然后报告如下所示:

Detected memory leaks!
Dumping objects ->
\memleak_malloc\main.cpp(10) : {74} client block at 0x009C1A90, subtype 0, 100 bytes long.
 Data: <ABC leak2       > 41 42 43 20 6C 65 61 6B 32 00 00 00 00 00 00 00
\memleak_malloc\main.cpp(7) : {73} normal block at 0x009C4F50, 100 bytes long.
 Data: <ABC leak1       > 41 42 43 20 6C 65 61 6B 31 00 CD CD CD CD CD CD
Object dump complete.
于 2013-05-19T10:24:08.953 回答