我编写了一些实用程序代码来检测程序关闭时的内存泄漏。 detect_leaks.hpp 和 cpp 包含进行设置的函数,在程序中您只需在程序启动时调用 start_detecting() 函数即可。
请注意,此代码使用 Microsoft 调试功能,因此仅适用于 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_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.
最佳答案
抱歉提问。我从另一个 SO 问题中找到了答案。
很方便,你就
#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.
关于c++ - 如何覆盖常规 malloc,以便在内存泄漏打印输出中打印行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633542/