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

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

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

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


当前回答

通常,独立应用程序中的内存泄漏不是致命的,因为它会在程序退出时被清除。

对于那些被设计为不退出的服务器程序,您该如何处理?

如果你是那种不设计和实现资源分配和释放正确的代码的程序员,那么我不想与你或你的代码有任何关系。如果您不关心清理泄漏的内存,那么锁呢?你也把他们留在那里吗?你是否在不同的目录中放置了一堆临时文件?

泄露内存并让程序清理?不。绝对不是。这是一个坏习惯,会导致bug、bug、更多的bug。

自己收拾干净。你妈已经不在这里工作了。

其他回答

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

即使您确定“已知的”内存泄漏不会造成严重破坏,也不要这样做。在最好的情况下,它会为你在不同的时间和地点犯下类似的、可能更严重的错误铺平道路。

对我来说,问这个问题就像问“我可以在凌晨3点没有人的时候闯红灯吗?”当然,在那个时候它可能不会造成任何麻烦,但它将为你在高峰时间做同样的事情提供一个杠杆!

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

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

看来你对“内存泄漏”的定义是“我自己不清理的内存”。所有现代操作系统都会在程序退出时释放它。然而,由于这是一个c++问题,您可以简单地将所讨论的内存包装在适当的std::auto_ptr中,当它超出作用域时将调用delete。