在C或c++应用程序中出现内存泄漏是可以接受的吗?

如果分配一些内存并一直使用到应用程序中的最后一行代码(例如,全局对象的析构函数),会怎样?只要内存消耗不随时间增长,那么当应用程序终止时(在Windows、Mac和Linux上),是否可以信任操作系统为您释放内存?如果内存一直被使用,直到被操作系统释放,您会认为这是真正的内存泄漏吗?

如果是第三方库将这种情况强加给您,该怎么办?会拒绝使用第三方库,不管它有多好?

我只看到了一个实际的缺点,那就是这些良性泄漏将在内存泄漏检测工具中显示为误报。


当前回答

这是一个非常特定的领域,几乎不值得回答。动动你的脑袋。

航天飞机操作系统:不,不允许内存泄漏 快速开发概念验证代码:修复所有这些内存泄漏是浪费时间。

还有一系列的中间情况。

延迟产品发布以修复除最严重内存泄漏外的所有内存泄漏的机会成本($$$)通常会让“草率或不专业”的感觉相形见绌。你的老板付钱给你是为了给他赚钱,而不是为了得到温暖、模糊的感觉。

其他回答

最佳实践是始终释放所分配的空间,特别是在编写旨在在整个系统正常运行期间运行的内容时,即使在退出之前进行清理。

这是一个非常简单的规则。以无泄漏为目标进行编程,可以很容易地发现新的泄漏。你会卖给别人一辆你自己造的车吗?你知道它一熄火就会喷到地上?:)

清理函数中的一些if () free()调用是廉价的,为什么不使用它们呢?

我想,如果你正在编写一个打算泄漏内存的程序(即测试内存泄漏对系统性能的影响),这是没有问题的。

规则很简单:如果你用完了一些内存,就清理它。 有时,即使我们稍后需要一些实例,但我们注意到我们会大量使用内存,所以它会影响性能,因为交换到磁盘,我们可以将数据存储到磁盘文件中,然后重新加载它们,有时这种技术会优化你的程序。

如果您的代码有任何内存泄漏,即使是已知的“可接受的”泄漏,那么使用任何内存泄漏工具来查找“真正的”泄漏将会非常麻烦。就像留下“可接受的”编译器警告会使查找新的“真正的”警告更加困难一样。

You have to first realize that there's a big difference between a perceived memory leak and an actual memory leak. Very frequently analysis tools will report many red herrings, and label something as having been leaked (memory or resources such as handles etc) where it actually isn't. Often times this is due to the analysis tool's architecture. For example, certain analysis tools will report run time objects as memory leaks because it never sees those object freed. But the deallocation occurs in the runtime's shutdown code, which the analysis tool might not be able to see.

尽管如此,仍然会有一些时候,您会遇到实际的内存泄漏,这些泄漏要么很难发现,要么很难修复。现在的问题是,是否可以将它们保留在代码中?

The ideal answer is, "no, never." A more pragmatic answer may be "no, almost never." Very often in real life you have limited number of resources and time to resolve and endless list of tasks. When one of the tasks is eliminating memory leaks, the law of diminishing returns very often comes in to play. You could eliminate say 98% of all memory leaks in an application in a week, but the remaining 2% might take months. In some cases it might even be impossible to eliminate certain leaks because of the application's architecture without a major refactoring of code. You have to weigh the costs and benefits of eliminating the remaining 2%.