关于内存泄露的检查

来源:互联网 发布:ac尼尔森数据分析2016 编辑:程序博客网 时间:2024/04/30 09:01

今天装完DX9SDK后在samples下找了个名叫pick的工程看看,发现了以下代码:

 // Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

 

这个函数功能定义在网上也有人不只从哪copy来的:

Retrieves or modifies the state of the _crtDbgFlag flag to control the allocation behavior of the debug heap manager (debug version only). 

The _CrtSetDbgFlag function allows the application to control how the debug heap manager tracks memory allocations by modifying the bit fields of the _crtDbgFlag flag. By setting the bits (turning on), the application can instruct the debug heap manager to perform special debugging operations, including checking for memory leaks when the application exits and reporting if any are found, simulating low-memory conditions by specifying that freed memory blocks should remain in the heap's linked list, and verifying the integrity of the heap by inspecting each memory block at every allocation request. When _DEBUG is not defined, calls to _CrtSetDbgFlag are removed during preprocessing.

 

我不太明白以上文段中的"通过那些应该保留在堆栈列表中的已经释放的内存块模拟低内存条件"是什么意思,还是我翻译不合理?

 

记得在原公司时因为gdi绘图从网上copy一堆代码直接f5,恰好被progammer leader发现,我当场就被责备了一通的,因为一大堆Memory leak,弄得我左右皆不好解释,当初他老人家就告诉我一个检测宏,说是crt什么的,我说我们的显示器都是LED了,crt和386是同一时代的,冏冏,

所以,我犹为清楚

 

其实以上皆为废话,以下才是朋友想要了解的:

 

此函数参数表有:

 

#define _CRTDBG_ALLOC_MEM_DF        0x01  /* Turn on debug allocation */
#define _CRTDBG_DELAY_FREE_MEM_DF   0x02  /* Don't actually free memory */
#define _CRTDBG_CHECK_ALWAYS_DF     0x04  /* Check heap every alloc/dealloc */
#define _CRTDBG_RESERVED_DF         0x08  /* Reserved - do not use */
#define _CRTDBG_CHECK_CRT_DF        0x10  /* Leak check/diff CRT blocks */
#define _CRTDBG_LEAK_CHECK_DF       0x20  /* Leak check at program exit */

 

在MFC中,会在调试窗口中显示出泄露处所在文件多少行号,双击可以定位,但在非MFC程序中则需要定义如下:

#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif

 

在泄露报告

Detected memory leaks!
Dumping objects
->
c:/yzw/test.cpp(131
) : {94} normal block at 0x003C4410, 40 bytes long.
Data:
<                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

中的{94}是指在第94次内存分配操作时发生了泄漏(内存申请操作不仅仅是你自己new了多少次,就只申请多少次,初始化应用程序时c或c++本身会有一些内存申请操作),可以预先通过函数:_CrtSetBreakAlloc(94)的调用在94次内存申请操作泄露处断点自动停下来,可以查函数调用栈进一步分析,但此函数在多线程中可能未必能如愿以偿,因为此函数要求多次执行过程的内存分配顺序不会发生变化.

 

最后别忘了加头文件:crtdbg.h