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

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

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

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


当前回答

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.

其他回答

在以前,我可能会说是的,在你的程序中让一些内存泄漏有时是可以接受的(它仍然是快速原型),但现在有了5到6次的经验,即使是跟踪最小的泄漏也会发现一些真正严重的功能错误。在数据实体的生命周期还不清楚的情况下,让程序发生泄漏,显示出严重缺乏分析。总之,了解程序中发生了什么总是一个好主意。

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.

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

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

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

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

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

我看到了和所有场景问题一样的问题,比如:当程序改变时,会发生什么?突然,这个小内存泄漏被调用了1000万次,而程序的结尾在不同的地方,所以它很重要?如果它在库中,那么请向库维护者记录错误,不要在您自己的代码中泄漏。

我完全同意JohnMcG的观点,只是想补充一点,我自己也有问题,无法及时发现真实的、潜在的严重内存泄漏,只是因为人们已经接受了良性的内存泄漏。随着时间的推移,这些病毒变得如此之多,在大量的良性病毒中发现严重病毒就变得越来越困难。

因此,至少为了你的程序员同事(也是为了你自己的未来),请尽快消除它们。