预防和检测内存泄漏的方法:

来源:互联网 发布:儿童计算机教育 知乎 编辑:程序博客网 时间:2024/06/10 08:35

预防和检测内存泄漏的方法:
1. 良好的代码规范
2. c++可以利用 一些语言特性 auto_ptr 或者 将资源封装在对象里
3. c 可以用 gc 库 GC_MALLOC 实现gabage collector
4. 一些优秀的 诊断软件 bound checker (VC) valgrind (GCC)

另外用以下方法,当有内存泄漏时,可以在调试时看到输出信息。

DebugNew.h

C/C++ code
#ifndef __DEBUGNEW_H_33164B60_A660_4B88_AEA3_270C97F24B12_INCLUDED__#define __DEBUGNEW_H_33164B60_A660_4B88_AEA3_270C97F24B12_INCLUDED__#ifdef  __cplusplus    #ifdef _DEBUG        #include <crtdbg.h>        // Overload operator new        inline void * __cdecl operator new(size_t nSize, const char * lpszFileName, int nLine)        {            int nFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);            nFlag |= _CRTDBG_LEAK_CHECK_DF;            _CrtSetDbgFlag(nFlag);            return ::operator new(nSize, _NORMAL_BLOCK, lpszFileName, nLine);        };        #define DEBUG_NEW new(__FILE__, __LINE__)        #define new DEBUG_NEW        // Overload operator delete (, or the compiler will give warning.)        inline void __cdecl operator delete(void *pData, const char * lpszFileName, int nLine)        {            ::operator delete(pData);        }    #endif  // #ifdef _DEBUG#endif  // #ifdef  __cplusplus       #endif // #ifndef __DEBUGNEW_H_33164B60_A660_4B88_AEA3_270C97F24B12_INCLUDED__

包含此文件,调试模式运行,结束后看输出,如果有内存泄漏将会看到。
比如:

Main.h

C/C++ code
// DebugNew.h might be in conflict with some other codes, such as STL.// If you use STL, do include STL header files before DebugNew.h.#include "DebugNew.h"int main(){    new int;    return 0;}

然后会看到输出:
Detected memory leaks!
Dumping objects ->

x:/.../main.cpp(7) : {120} normal block at 0x00396220, 4 bytes long.
Data: <    > CD CD CD CD
Object dump complete.


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/douyangyang/archive/2009/04/02/4042312.aspx