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

预防和检测内存泄漏的方法:
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值