我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。
我通常会在代码中出现内存泄漏。
通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。
因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。
我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?
我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。
我通常会在代码中出现内存泄漏。
通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。
因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。
我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?
当前回答
回答你问题的第二部分,
是否有任何标准或程序可以确保程序中没有内存泄漏。
是的,有。这是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.
这意味着当对象超出作用域时,它将被自动销毁,并释放和清理它的资源。
如果在整个代码中始终这样做,就不会有任何内存泄漏。所有可能泄露的内容都绑定到析构函数,该析构函数保证在控件离开声明对象的作用域时被调用。
其他回答
您可以使用Valgrind工具来检测内存泄漏。
此外,要找到特定函数中的漏洞,请在函数末尾使用exit(0),然后使用Valgrind运行它
`$` valgrind ./your_CPP_program
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.
确保成功释放了所有堆内存。如果您从未在堆上分配内存,则不需要这样做。如果你这样做,计算你malloc内存的次数,并计算你释放内存的次数。
如果使用gcc,则有gprof可用。
我想知道程序员如何发现内存泄漏
有些人使用工具,有些人做你做的事情,也可以通过同行代码审查
是否应该遵循某种标准或过程来确保程序中没有内存泄漏
对我来说:每当我创建动态分配对象时,我总是把释放代码放在后面,然后在中间填充代码。如果您确定之间的代码中不会出现异常,那么这样做是可以的。否则,我会使用try-finally(我不经常使用c++)。
在应用程序代码中不应该使用“new”或“delete”。相反,应该创建一个使用管理器/工作人员习惯用法的新类型,其中管理器类分配和释放内存,并将所有其他操作转发给工作人员对象。
不幸的是,这比它应该做的要多,因为c++没有“operator .”的重载。如果存在多态,则工作量更大。
但是这样做是值得的,因为这样您就不必担心内存泄漏,这意味着您甚至不需要寻找它们。