在C或c++应用程序中出现内存泄漏是可以接受的吗?
如果分配一些内存并一直使用到应用程序中的最后一行代码(例如,全局对象的析构函数),会怎样?只要内存消耗不随时间增长,那么当应用程序终止时(在Windows、Mac和Linux上),是否可以信任操作系统为您释放内存?如果内存一直被使用,直到被操作系统释放,您会认为这是真正的内存泄漏吗?
如果是第三方库将这种情况强加给您,该怎么办?会拒绝使用第三方库,不管它有多好?
我只看到了一个实际的缺点,那就是这些良性泄漏将在内存泄漏检测工具中显示为误报。
首先,让我们把定义更正一下。内存泄漏是指动态分配内存,例如使用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;
}
你分配内存,使用它直到程序结束。这不是内存泄漏;它不会损害程序,并且当程序终止时,所有的内存将被自动清除。
一般来说,应该避免内存泄漏。首先,因为就像你头顶上的高度和飞机库里的燃料一样,已经泄漏且无法恢复的内存是无用的;其次,在一开始就正确编码,不泄漏内存,比后来发现内存泄漏要容易得多。
I'm going to give the unpopular but practical answer that it's always wrong to free memory unless doing so will reduce the memory usage of your program. For instance a program that makes a single allocation or series of allocations to load the dataset it will use for its entire lifetime has no need to free anything. In the more common case of a large program with very dynamic memory requirements (think of a web browser), you should obviously free memory you're no longer using as soon as you can (for instance closing a tab/document/etc.), but there's no reason to free anything when the user selects clicks "exit", and doing so is actually harmful to the user experience.
为什么?释放内存需要接触内存。即使您的系统的malloc实现碰巧没有在分配的内存块附近存储元数据,您也可能会遍历递归结构,只是为了找到所有需要释放的指针。
Now, suppose your program has worked with a large volume of data, but hasn't touched most of it for a while (again, web browser is a great example). If the user is running a lot of apps, a good portion of that data has likely been swapped to disk. If you just exit(0) or return from main, it exits instantly. Great user experience. If you go to the trouble of trying to free everything, you may spend 5 seconds or more swapping all the data back in, only to throw it away immediately after that. Waste of user's time. Waste of laptop's battery life. Waste of wear on the hard disk.
这不仅仅是理论上的。每当我发现自己加载了太多的应用程序,磁盘开始抖动时,我甚至不会考虑点击“退出”。我以最快的速度到达一个终端,输入killall -9…因为我知道"退出"只会让情况更糟。