我编写了一些实用程序代码来检测程序关闭时的内存泄漏。Detect_leaks.hpp和CPP包含设置的函数,在程序中你只需要在程序开始时调用start_detection()函数。
注意这段代码使用了微软的调试函数,所以只适用于Windows。
我的报告打印出文件中包含泄漏的new分配的行,因为我有这个:
#define new new(_CLIENT_BLOCK,__FILE__, __LINE__)
但是如何对malloc做同样的事情呢?如果需要的话,我也不介意把名字改成mmalloc。是的,我知道我不应该使用malloc,但是我有一些非常旧的代码。
下面是到目前为止的代码:detect_leaks.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__
detect_leaks.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_mallocmain.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.
不好意思。我从另一个问题中找到了答案。
这很方便,你只需
#define _CRTDBG_MAP_ALLOC
然后报告是这样的:
Detected memory leaks!
Dumping objects ->
memleak_mallocmain.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_mallocmain.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.