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

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

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

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


当前回答

从历史上看,在某些边缘情况下,它在某些操作系统上确实很重要。这些边缘情况在未来可能会存在。

Here's an example, on SunOS in the Sun 3 era, there was an issue if a process used exec (or more traditionally fork and then exec), the subsequent new process would inherit the same memory footprint as the parent and it could not be shrunk. If a parent process allocated 1/2 gig of memory and didn't free it before calling exec, the child process would start using that same 1/2 gig (even though it wasn't allocated). This behavior was best exhibited by SunTools (their default windowing system), which was a memory hog. Every app that it spawned was created via fork/exec and inherited SunTools footprint, quickly filling up swap space.

其他回答

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.

首先,让我们把定义更正一下。内存泄漏是指动态分配内存,例如使用malloc(),并且所有对内存的引用都在没有相应的free的情况下丢失。制作一个简单的方法是这样的:

#define BLK ((size_t)1024)
while(1){
    void * vp = malloc(BLK);
}

注意,每次在while(1)循环中,分配1024(+开销)字节,并将新地址分配给vp;没有指向之前malloc 'Ed块的剩余指针。这个程序保证运行到堆用完为止,并且没有办法恢复任何malloc'ed内存。内存从堆中“泄漏”出来,再也看不见了。

你所描述的,听起来就像

int main(){
    void * vp = malloc(LOTS);
    // Go do something useful
    return 0;
}

你分配内存,使用它直到程序结束。这不是内存泄漏;它不会损害程序,并且当程序终止时,所有的内存将被自动清除。

一般来说,应该避免内存泄漏。首先,因为就像你头顶上的高度和飞机库里的燃料一样,已经泄漏且无法恢复的内存是无用的;其次,在一开始就正确编码,不泄漏内存,比后来发现内存泄漏要容易得多。

也许是在细枝末节:如果您的应用程序运行在UNIX上,可能会变成僵尸怎么办?在这种情况下,内存不会被操作系统回收。所以我说你应该在程序退出之前重新分配内存。

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

If I understood correctly, you don't explicitly free memory (which can be freed because you still have a pointer) and rely on OS to free it during process termination. Though this may seem okay for simple program, consider the situation where your code is moved into a library and becomes a part of some resident daemon process running 24/7. Say this daemon spawns a thread each time it needs to do something useful using your code and say it spawns thousands of threads every hour. In this case you will get real memory leak.

不幸的是,这种情况在现实生活中并非不可能,一致的内存管理技术可能会使您的生活更轻松。

如果它是故意的,它真的不是一个泄漏,它不是一个问题,除非它是一个相当大的内存,或者可以增长到一个相当大的内存。在程序的生命周期内不清理全局分配是很常见的。如果泄漏是在服务器或长时间运行的应用程序中,随着时间的推移而增长,那么这就是一个问题。