MFC程序中检查内存泄漏的手段
2006-08-21 16:52
274 查看
CMemoryState
CMemoryState does not have a base class.CMemoryState provides a convenient way to detect memory leaks in your program. A “memory leak” occurs when memory for an object is allocated on the heap but not deallocated when it is no longer required. Such memory leaks can eventually lead to out-of-memory errors. There are several ways to allocate and deallocate memory in your program:
Using the malloc/free family of functions from the run-time library.
Using the Windows API memory management functions, LocalAlloc/LocalFree and GlobalAlloc/GlobalFree.
Using the C++ new and delete operators.
The CMemoryState diagnostics only help detect memory leaks caused when memory allocated using the new operator is not deallocated using delete. The other two groups of memory-management functions are for non-C++ programs, and mixing them with new and delete in the same program is not recommended. An additional macro, DEBUG_NEW, is provided to replace the new operator when you need file and line-number tracking of memory allocations. DEBUG_NEW is used whenever you would normally use the new operator.
As with other diagnostics, the CMemoryState diagnostics are only available in debug versions of your program. A debug version must have the _DEBUG constant defined.
If you suspect your program has a memory leak, you can use the Checkpoint, Difference, and DumpStatistics functions to discover the difference between the memory state (objects allocated) at two different points in program execution. This information can be useful in determining whether a function is cleaning up all the objects it allocates.
If simply knowing where the imbalance in allocation and deallocation occurs does not provide enough information, you can use the DumpAllObjectsSince function to dump all objects allocated since the previous call to Checkpoint. This dump shows the order of allocation, the source file and line where the object was allocated (if you are using DEBUG_NEW for allocation), and the derivation of the object, its address, and its size. DumpAllObjectsSince also calls each object’s Dump function to provide information about its current state.
在你怀疑有问题的代码前申明一个CMemoryState对象,调用其Checkpoint()函数,在你
认为有问题代码结束后再申明一个CMemoryState对象,再调用Checkpoint()函数,申明
第3个CMemoryState对象,调用其Difference()函数,就可以检查有无内存泄漏,若有
调用DumpStatistics()函数输出统计结果。
相关文章推荐
- 用MFC时,如果程序崩溃,检查内存,然后注意GDI数量,在任务管理器里选项-查看列-GDI数量
- C程序中检查内存泄漏的方法
- 程序代码检查内存泄漏方法
- 检查MFC程序的内存泄露
- 检查程序是否有内存泄漏:valgrind 的用法
- 检查MFC程序的内存泄露
- 检查MFC程序的内存泄露
- 检查MFC程序的内存泄露
- MFC程序内存泄露检查
- 检查MFC程序的内存泄露
- 检查MFC程序的内存泄露
- 关于在VS2008以下版本的MFC程序使用VS 2008 FeaturePack出现内存泄露的理解
- 使用OpenCv库的MFC程序在退出后报内存泄露 可能解决方法
- DLL中单例模式存在的非模态CPropertySheet对话框在程序关闭时产生内存泄漏
- 使用 .NET Profiler API 检查并优化程序的内存使用
- Linux下几款C++程序中的内存泄露检查工具
- C++程序检测内存泄漏的方法分享
- 检查程序是否驻留内存的办法
- 一种通用的终端设备内存泄漏检查方案
- mtrace检查内存泄漏