C++ 检测内存泄露
假如是用MFC的程序的话,很简单。默认的就有内存泄露检测的功能。
我们用VS2005生成了一个MFC的对话框的程序,发现他可以自动的检测内存泄露.不用我们做任何特殊的操作. 仔细观察,发现在每个CPP文件中,都有下面的代码:
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
DEBUG_NEW 这个宏定义在afx.h文件中,就是它帮助我们定位内存泄漏。
Detected memory leaks!
Dumping objects ->
d:/code/mfctest/mfctest.cpp(80) : {157} normal block at 0x003AF170, 4 bytes long.
Object dump complete.
我试了下用VisualStudio建立的Win32 Console Application和Win32 Project项目,结果都不能检测出内存泄露。
下面一步一步来把程序的内存泄露检测的机制建立起来。
首先,我们需要知道C运行库的Debug版本提供了许多检测功能,使得我们更容易的Debug程序。在MSDN中有专门的章节讲这个,叫做Debug Routines,建议大家先看看里面的内容吧。
我们会用到里面很重要的几个函数。其中最重要的是 _CrtDumpMemoryLeaks();自己看MSDN里的帮助吧。使用这个函数,需要包含头文件crtdbg.h
该函数只在Debug版本才有用,当在调试器下运行程序时,_CrtDumpMemoryLeaks 将在“Output(输出)”窗口中显示内存泄漏信息.写段代码试验一下吧,如下:
#include "stdafx.h"
#include
int _tmain(int argc, _TCHAR* argv[])
{
}
Detected memory leaks!
Dumping objects ->
{112} normal block at 0x003AA770, 4 bytes long.
Object dump complete.
#include "stdafx.h"
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
int _tmain(int argc, _TCHAR* argv[])
{
}
Detected memory leaks!
Dumping objects ->
d:/code/consoletest/consoletest.cpp(21) : {112} client block at 0x003A38B0, subtype 0, 4 bytes long.
Object dump complete.
int _tmain(int argc, _TCHAR* argv[])
{
}
所以除了在必要的时候Dump出内存信息外,最重要的就是在程序退出的时候需要掉用一次_CrtDumpMemoryLeaks();
#include "stdafx.h"
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
class Test
{
public:
};
int _tmain(int argc, _TCHAR* argv[])
{
}
#include "stdafx.h"
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
class Test
{
public:
};
int _tmain(int argc, _TCHAR* argv[])
{
}
该语句在程序退出时自动调用 _CrtDumpMemoryLeaks。必须同时设置 _CRTDBG_ALLOC_MEM_DF 和 _CRTDBG_LEAK_CHECK_DF.
#include "stdafx.h"
#include
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
void Exit()
{
}
int _tmain(int argc, _TCHAR* argv[])
{
}
#pragma once
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include
#include
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif