当前位置: 代码迷 >> VC >> .net2003中内存泄露如何检测
  详细解决方案

.net2003中内存泄露如何检测

热度:7468   发布时间:2013-02-25 00:00:00.0
.net2003中内存泄露怎么检测?
写了一个简单的检测内存泄露的控制台程序:
#include   "stdafx.h "

//for   memory   leak   check
#define   _CRTDBG_MAP_ALLOC   //使生成的内存dump包含内存块分配的具体代码为止
#include <stdlib.h>  
#include <crtdbg.h>  

int   _tmain(int   argc,   _TCHAR*   argv[])
{
_CrtSetDbgFlag(   _CRTDBG_ALLOC_MEM_DF   |   _CRTDBG_LEAK_CHECK_DF   );
int   *q   =   new   int[2];
q[0]   =   1;
q[1]   =   2;

//_CrtDumpMemoryLeaks();
return   0;

}

按F5运行后输出窗口得到有关内存泄露的信息如下:
Detected   memory   leaks!
Dumping   objects   ->
e:\microsoft   visual   studio   .net   2003\vc7\include\crtdbg.h(692)   :   {41}   normal   block   at   0x003710B0,   8   bytes   long.
  Data:   <                 >   01   00   00   00   02   00   00   00  
Object   dump   complete.

请问检测到的内存泄露位置为什么只有e:\microsoft   visual   studio   .net   2003\vc7\include\crtdbg.h(692)处
而网上查找到的其他人按此方法可以定位到用户编写的代码处,如:E:\TestMemLeak\TestDlg.cpp(70)   :   {59}   normal   block   at   0x00881710,   200   bytes   long.
是我什么地方写错了吗?请问怎样做可以将内存泄露的具体位置(如定位到:int   *q   =   new   int[2];处)显示出来


------解决方案--------------------------------------------------------
在文件头部加上:
#include <crtdbg.h>

#ifdef _DEBUG
#define DEBUG_NEW new (_NORMAL_BLOCK, THIS_FILE, __LINE__)
#endif

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif