我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。
我通常会在代码中出现内存泄漏。
通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。
因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。
我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?
我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。
我通常会在代码中出现内存泄漏。
通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。
因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。
我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?
当前回答
Valgrind http://valgrind.org/
and
广东发展银行 http://www.gnu.org/software/gdb/
其他回答
确保成功释放了所有堆内存。如果您从未在堆上分配内存,则不需要这样做。如果你这样做,计算你malloc内存的次数,并计算你释放内存的次数。
运行“Valgrind”可以:
1)帮助识别内存泄漏-显示您有多少内存泄漏,并指出代码中泄漏内存分配的行。
2)指出错误的释放内存的尝试(例如不正确的delete调用)
“Valgrind”使用说明
1)在这里获得valgrind。
2)使用-g标志编译代码
3)在shell中运行:
valgrind --leak-check=yes myprog arg1 arg2
其中"myprog"是你编译的程序,arg1, arg2是你程序的参数。
4)结果是一个调用malloc/new的列表,没有后续调用free delete。
例如:
==4230== at 0x1B977DD0: malloc (vg_replace_malloc.c:136)
==4230== by 0x804990F: main (example.c:6)
告诉您在哪一行(未释放的)调用了malloc。
正如其他人指出的那样,确保对于每个新的/malloc调用,都有一个后续的delete/free调用。
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.
在Windows上,你可以使用CRT调试堆。
是否有任何标准或程序可以确保程序中没有内存泄漏。
是的,不要使用手动内存管理(如果你曾经手动调用delete或delete[],那么你做错了)。使用RAII和智能指针,将堆分配限制到绝对最小值(大多数时候,自动变量就足够了)。
在visual studio中,有一个内置的内存泄漏检测器,称为C运行时库。当主函数返回后程序退出时,CRT将检查应用程序的调试堆。如果在调试堆上仍然分配了任何块,那么就存在内存泄漏。 本论坛讨论了在C/ c++中避免内存泄漏的一些方法。