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

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

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

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

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


当前回答

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

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

`$` valgrind ./your_CPP_program 

其他回答

Download Debugging Tools for Windows. Use the gflags utility to turn on user-mode stack traces. Use UMDH to take multiple snapshots of your program's memory. Take a snapshot before memory gets allocated, and take a second snapshot after a point at which you believe that your program has leaked memory. You might want to add pauses or prompts in your program to give you a chance to run UMDH and take the snapshots. Run UMDH again, this time in its mode that does a diff between the two snapshots. It will then generate a report containing the call stacks of suspected memory leaks. Restore your previous gflags settings when you're done.

UMDH会给你比CRT调试堆更多的信息,因为它会监视整个进程的内存分配;它甚至可以告诉您第三方组件是否泄漏。

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

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

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

回答你问题的第二部分,

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

是的,有。这是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.

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

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

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

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

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

运行“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调用。