我是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.

其他回答

您可以使用Valgrind工具来检测内存泄漏。

此外,要找到特定函数中的漏洞,请在函数末尾使用exit(0),然后使用Valgrind运行它

`$` valgrind ./your_CPP_program 

Valgrind http://valgrind.org/

and

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

AddressSanitizer (ASan)是一种快速的内存错误检测器。 它可以发现C/ c++程序中的use-after-free和{heap,stack,global}-buffer溢出错误。它发现:

在free之后使用(悬空指针解引用) 堆缓冲区溢出 堆栈缓冲区溢出 全局缓冲区溢出 退货后使用 初始化顺序错误

这个工具很快。仪器程序的平均速度为~2倍。

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

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

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

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