9

内存泄漏快速定位方法

 3 years ago
source link: https://blog.csdn.net/china_video_expert/article/details/70163772
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

内存泄漏快速定位方法

reprint.png
叶广明_微信ye_guangming 2017-04-13 23:51:28 articleReadEyes.png 1218
分类专栏: C语言进阶

主要方法:利用系统带的函数:EnableMemLeakCheck() 和函数重载,能快速准备的定位到内存泄漏的地方,方法简单且实用,值得借用。

#include <crtdbg.h>

#ifdef_DEBUG    //重载一下new函数,这样能得到使用new 开辟空间而发生泄漏的文件和所在行,这就是定位
#define new   new(_NORMAL_BLOCK,__FILE__, __LINE__)
#endif

void EnableMemLeakCheck()  //用于检测是否有内存泄漏。
{

  _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)|_CRTDBG_LEAK_CHECK_DF);

void main()
{
   EnableMemLeakCheck();
   int *leak = new int[10];
}

运行后得到的消息:

Loaded 'C:\WINNT\System32\ntdll.dll', no matchingsymbolic information found.
Loaded 'C:\WINNT\system32\kernel32.dll', no matching symbolicinformation found.
Detected memory leaks!
Dumping objects ->
D:\DS_Learn\meleak\test1.cpp(19) : {39}normal block at 0x00430120, 40 bytes long.
 Data:<               > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CDCD
Object dump complete.
The thread 0x91C has exited with code 4391200 (0x430120).
The program 'D:\DS_LEARN\meleak\Debug\meleak.exe' has exited withcode 4391200 (0x430120).

很快就能定位到内存泄漏的地方。

我原来也利用相关的方法,在C代码中,重载malloc 和free,也能很好的检测有没有内存泄漏和发生泄漏的地方,方法都很简单,其实自己在写代码注意一下结构,还是很容易避免发生内存泄漏。

   平时喜欢用这样的结构:

   projectname_init(); //在初始化时,开辟好空间,对project中一些变量,如结构体开辟空间

   projectname_process();  //作相关的处理

   projectname_uninit();    //结束程序运行,释放所以动态分配的空间。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK