我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。
我通常会在代码中出现内存泄漏。
通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。
因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。
我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?
我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。
我通常会在代码中出现内存泄漏。
通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。
因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。
我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?
当前回答
Search your code for occurrences of new, and make sure that they all occur within a constructor with a matching delete in a destructor. Make sure that this is the only possibly throwing operation in that constructor. A simple way to do this is to wrap all pointers in std::auto_ptr, or boost::scoped_ptr (depending on whether or not you need move semantics). For all future code just ensure that every resource is owned by an object that cleans up the resource in its destructor. If you need move semantics then you can upgrade to a compiler that supports r-value references (VS2010 does I believe) and create move constructors. If you don't want to do that then you can use a variety of tricky techniques involving conscientious usage of swap, or try the Boost.Move library.
其他回答
Search your code for occurrences of new, and make sure that they all occur within a constructor with a matching delete in a destructor. Make sure that this is the only possibly throwing operation in that constructor. A simple way to do this is to wrap all pointers in std::auto_ptr, or boost::scoped_ptr (depending on whether or not you need move semantics). For all future code just ensure that every resource is owned by an object that cleans up the resource in its destructor. If you need move semantics then you can upgrade to a compiler that supports r-value references (VS2010 does I believe) and create move constructors. If you don't want to do that then you can use a variety of tricky techniques involving conscientious usage of swap, or try the Boost.Move library.
Valgrind http://valgrind.org/
and
广东发展银行 http://www.gnu.org/software/gdb/
在Windows上,你可以使用CRT调试堆。
是否有任何标准或程序可以确保程序中没有内存泄漏。
是的,不要使用手动内存管理(如果你曾经手动调用delete或delete[],那么你做错了)。使用RAII和智能指针,将堆分配限制到绝对最小值(大多数时候,自动变量就足够了)。
在visual studio中,有一个内置的内存泄漏检测器,称为C运行时库。当主函数返回后程序退出时,CRT将检查应用程序的调试堆。如果在调试堆上仍然分配了任何块,那么就存在内存泄漏。 本论坛讨论了在C/ c++中避免内存泄漏的一些方法。
MTuner是一个免费的多平台内存分析、泄漏检测和分析工具,支持MSVC、GCC和Clang编译器。功能包括:
基于时间轴的内存使用历史和活动内存块 强大的内存操作过滤基于堆,内存标签,时间范围等。 SDK手动仪表与完整的源代码 通过命令行使用支持持续集成 调用堆栈树和树映射导航 更多。
用户可以通过GCC或Clang cross配置任何软件定位平台 编译器。MTuner内置对Windows、PlayStation 4和PlayStation 3平台的支持。