Win32 下内存泄漏检测的一个方法

来源:互联网 发布:网络推广怎么拿提成 编辑:程序博客网 时间:2024/04/19 18:08

要使用纯Win32下的C++写程序,碰到第二个问题(第一个问题先不说了:)),如何得知没有内存泄漏呢?

用MFC的话,很简单,有自带的。那Win32的程序呢?

 

Google了很多,找不到比较爽的

 

突然间的Idea:MFC不是开源的,何不把它那一套东西挖出来呢?

 

呵呵,效果还是有的,请大家往下看。

 

先写个很简单的程序:

 

很显然,结束程序后,不会有任何提示内存问题。

 

再看下面的:

程序结束后,提示:

Detected memory leaks!
Dumping objects ->
{117} normal block at 0x00397988, 40 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

 

 

大家注意到了 _CrtSetDbgFlag(...) 这个函数了,对的,它的说明如下:

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

 

_CRTDBG_LEAK_CHECK_DF 说明如下:

Perform automatic leak checking at program exit through a call to _CrtDumpMemoryLeaks and generate an error report if the application failed to free all the memory it allocated.

 :) 具体我就不解释了(因为已经很清楚了啊!),这个函数是在跟踪MFC的代码后发现的。有兴趣的朋友也可以自己试下

 

 

不过,还是不太完美!!!

MFC中的提示可以显示内存泄漏是哪一行等更具体的信息的。现在我们的实现还没有!

 

:)

原因是:我们提供把具体的内存分配信息给 heap Manager

 

 

请看下面的解决方法:

重写new,delete操作符,顺便把分配时的信息提供给heap manager

 

在 stdafx.h 中加入下面行

在stdafx.cpp 中加入:

 

 

最后,我们的文件如下:

 

 

运行后,结果如下:

Detected memory leaks!
Dumping objects ->
d:/anakin/temp/testmemleak/testmemleak/testmemleak.cpp(14) : {117} normal block at 0x00397988, 40 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

 

 

:) enjoy!

原创粉丝点击