我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。

我通常会在代码中出现内存泄漏。

通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。

因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。

我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?


当前回答

除了其他答案中提供的工具和方法之外,静态代码分析工具还可以用于检测内存泄漏(以及其他问题)。 Cppcheck是一个免费的健壮的工具。但是还有很多其他可用的工具。Wikipedia有一个静态代码分析工具列表。

其他回答

Valgrind http://valgrind.org/

and

广东发展银行 http://www.gnu.org/software/gdb/

确保成功释放了所有堆内存。如果您从未在堆上分配内存,则不需要这样做。如果你这样做,计算你malloc内存的次数,并计算你释放内存的次数。

有一些著名的编程技术可以帮助您将内存泄漏的风险降至最低:

if you have to do your own dynamic memory allocation, write new and delete always pairwise, and make sure the allocation/deallocation code is called pairwise avoid dynamic memory allocation if you can. For example, use vector<T> t whereever possible instead of T* t = new T[size] use "smart pointers" like boost smart pointers (http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/smart_ptr.htm) my personal favorite: make sure you have understood the concept of ownership of a pointer, and make sure that everywhere where you use pointers, you know which code entity is the owner learn which constructors / assignment operators are automatically created by the C++ compiler, and what that means if you have class that owns a pointer (or what that means if you have a class that contains a pointer to an object it does not own).

Visual Leak Detector (VLD)是一个免费的、健壮的、开源的Visual c++内存泄漏检测系统。

当您在Visual Studio调试器下运行程序时,Visual Leak Detector将在调试会话结束时输出内存泄漏报告。泄漏报告包括完整的调用堆栈,显示泄漏的内存块是如何分配的。双击调用堆栈中的一行,以跳转到编辑器窗口中的该文件和该行。

如果你只有崩溃转储,你可以使用Windbg !heap -l命令,它将检测泄漏的堆块。最好打开gflags选项:“创建用户模式堆栈跟踪数据库”,然后您将看到内存分配调用堆栈。

在Windows上,你可以使用CRT调试堆。

是否有任何标准或程序可以确保程序中没有内存泄漏。

是的,不要使用手动内存管理(如果你曾经手动调用delete或delete[],那么你做错了)。使用RAII和智能指针,将堆分配限制到绝对最小值(大多数时候,自动变量就足够了)。