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

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

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

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

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


当前回答

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

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

`$` valgrind ./your_CPP_program 

其他回答

如果使用gcc,则有gprof可用。

我想知道程序员如何发现内存泄漏

有些人使用工具,有些人做你做的事情,也可以通过同行代码审查

是否应该遵循某种标准或过程来确保程序中没有内存泄漏

对我来说:每当我创建动态分配对象时,我总是把释放代码放在后面,然后在中间填充代码。如果您确定之间的代码中不会出现异常,那么这样做是可以的。否则,我会使用try-finally(我不经常使用c++)。

在visual studio中,有一个内置的内存泄漏检测器,称为C运行时库。当主函数返回后程序退出时,CRT将检查应用程序的调试堆。如果在调试堆上仍然分配了任何块,那么就存在内存泄漏。 本论坛讨论了在C/ c++中避免内存泄漏的一些方法。

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.

回答你问题的第二部分,

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

是的,有。这是C和c++的主要区别之一。

在c++中,永远不要在用户代码中调用new或delete。RAII是一种非常常用的技术,它在很大程度上解决了资源管理问题。程序中的每一个资源(资源是任何需要获取,然后释放的东西:文件句柄,网络套接字,数据库连接,但也包括普通内存分配,在某些情况下,对API调用(BeginX()/EndX(), LockY(), UnlockY()))都应该包装在一个类中,其中:

构造函数获取资源(如果资源是内存分配,则调用new) 析构函数释放资源, 复制和赋值要么被阻止(通过将复制构造函数和赋值操作符设置为私有),要么被实现为正确工作(例如通过克隆底层资源)

然后,该类在本地、堆栈上或作为类成员实例化,而不是通过调用new和存储指针来实例化。

You often don't need to define these classes yourself. The standard library containers behave in this way as well, so that any object stored into a std::vector gets freed when the vector is destroyed. So again, don't store a pointer into the container (which would require you to call new and delete), but rather the object itself (which gives you memory management for free). Likewise, smart pointer classes can be used to easily wrap objects that just have to be allocated with new, and control their lifetimes.

这意味着当对象超出作用域时,它将被自动销毁,并释放和清理它的资源。

如果在整个代码中始终这样做,就不会有任何内存泄漏。所有可能泄露的内容都绑定到析构函数,该析构函数保证在控件离开声明对象的作用域时被调用。

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

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

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