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

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

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

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


当前回答

我同意vfilby -这要看情况。在Windows中,我们将内存泄漏视为相对严重的错误。但是,这很大程度上取决于分量。

例如,对于很少运行且运行时间有限的组件,内存泄漏不是很严重。这些组件运行,完成工作,然后退出。当它们退出时,所有内存都被隐式释放。

但是,服务或其他长期运行组件(如shell)中的内存泄漏非常严重。原因是这些bug会随着时间的推移“窃取”内存。恢复的唯一方法是重新启动组件。大多数人不知道如何重新启动服务或shell——所以如果他们的系统性能受到影响,他们就重新启动。

所以,如果你有一个泄漏-评估它的影响两种方式

你的软件和你的用户体验。 对于系统(和用户)来说,节省系统资源是非常重要的。 修复对维护和可靠性的影响。 在其他地方造成倒退的可能性。

前甲板

其他回答

如果分配内存并一直使用到程序的最后一行,这就不是泄漏。如果您分配内存并忘记它,即使内存数量没有增长,这也是一个问题。已分配但未使用的内存可能导致其他程序运行速度变慢或根本不运行。

我在高中上过一门C课,老师说当你malloc的时候一定要确保自由。

但是当我在大学里上另一门课的时候,教授说对那些只运行一秒钟的小程序不免费是可以的。 因此,我认为这不会损害您的程序,但免费提供强大、健康的代码是一种很好的实践。

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%.

如果一直使用到main()的尾部,则根本不是泄漏(当然,假设有受保护的内存系统!)

事实上,在进程关闭时释放对象绝对是你能做的最糟糕的事情……操作系统必须将你创建的每一页回退。关闭文件句柄,数据库连接,当然,但释放内存是愚蠢的。

Some great answers here. To add another perspective to this question, I'll address a case where memory leak is not only acceptable but desirable: in Windows drivers environment the developer provides a set of callbacks that are being run by the OS whenever required. One of the callbacks is a 'Shutdown' callback, which runs prior to system being shut off/restarted. Unlike standard situations, not only memory release is not necessary (system will be off in a moment), it's even discouraged - to make the shutdown as fast as possible and prevent the overhead of memory management.