我们都被教导必须释放每个已分配的指针。不过,我有点好奇不释放内存的真正代价。在一些明显的情况下,比如在循环内部或线程执行的一部分调用malloc()时,释放是非常重要的,这样就不会有内存泄漏。但是考虑下面两个例子:

首先,如果我有这样的代码:

int main()
{
    char *a = malloc(1024);
    /* Do some arbitrary stuff with 'a' (no alloc functions) */
    return 0;
}

真正的结果是什么?我的想法是进程死亡,然后堆空间也消失了,所以错过对free的调用没有什么坏处(然而,我确实认识到无论如何拥有它对于闭包、可维护性和良好实践的重要性)。我这样想对吗?

Second, let's say I have a program that acts a bit like a shell. Users can declare variables like aaa = 123 and those are stored in some dynamic data structure for later use. Clearly, it seems obvious that you'd use some solution that will calls some *alloc function (hashmap, linked list, something like that). For this kind of program, it doesn't make sense to ever free after calling malloc because these variables must be present at all times during the program's execution and there's no good way (that I can see) to implement this with statically allocated space. Is it bad design to have a bunch of memory that's allocated but only freed as part of the process ending? If so, what's the alternative?


当前回答

是的,你是对的,你的例子没有造成任何伤害(至少在大多数现代操作系统上没有)。进程退出后,操作系统将恢复进程分配的所有内存。

来源:分配和GC神话(PostScript警告!)

Allocation Myth 4: Non-garbage-collected programs should always deallocate all memory they allocate. The Truth: Omitted deallocations in frequently executed code cause growing leaks. They are rarely acceptable. but Programs that retain most allocated memory until program exit often perform better without any intervening deallocation. Malloc is much easier to implement if there is no free. In most cases, deallocating memory just before program exit is pointless. The OS will reclaim it anyway. Free will touch and page in the dead objects; the OS won't. Consequence: Be careful with "leak detectors" that count allocations. Some "leaks" are good!

也就是说,您应该尽量避免所有内存泄漏!

第二个问题:你的设计还可以。如果你需要存储一些东西直到你的应用程序退出,那么使用动态内存分配是可以的。如果您事先不知道所需的大小,就不能使用静态分配的内存。

其他回答

不释放变量并没有真正的危险,但是如果将一个内存块的指针分配给另一个内存块而不释放第一个块,第一个块将不再可访问,但仍然占用空间。这就是所谓的内存泄漏,如果您经常这样做,那么您的进程将开始消耗越来越多的内存,从其他进程占用系统资源。

如果进程是短期的,那么通常可以这样做,因为当进程完成时,所有分配的内存都会被操作系统回收,但我建议养成释放所有不再使用的内存的习惯。

你说得对,不会造成伤害,直接退出会更快

原因有很多:

All desktop and server environments simply release the entire memory space on exit(). They are unaware of program-internal data structures such as heaps. Almost all free() implementations do not ever return memory to the operating system anyway. More importantly, it's a waste of time when done right before exit(). At exit, memory pages and swap space are simply released. By contrast, a series of free() calls will burn CPU time and can result in disk paging operations, cache misses, and cache evictions.

关于未来代码重用的可能性,为毫无意义的操作的确定性辩护:这是一个考虑,但可以说这不是敏捷的方式。YAGNI !

在那方面你完全正确。在小的程序中,变量必须存在,直到程序结束,释放内存并没有真正的好处。

事实上,我曾经参与过一个项目,在这个项目中,程序的每次执行都非常复杂,但时间相对较短,决定只是保持分配内存,而不是因为错误地释放内存而破坏项目的稳定。

话虽如此,在大多数程序中,这并不是一个真正的选项,或者它会导致内存耗尽。

几乎每个现代操作系统都会在程序退出后恢复所有已分配的内存空间。我能想到的唯一例外可能是像Palm OS这样的东西,其中程序的静态存储和运行时内存几乎是一样的,所以不释放可能会导致程序占用更多的存储空间。(我只是在猜测。)

所以一般来说,这样做没有什么坏处,除了存储容量超过所需的运行时成本。当然,在您给出的示例中,您希望保留可能被使用的变量的内存,直到它被清除。

然而,一旦你不再需要内存,就立即释放内存,并在程序退出时释放你仍然拥有的内存,这被认为是一种很好的方式。它更像是一种了解您正在使用哪些内存的练习,并考虑是否仍然需要它。如果不进行跟踪,可能会出现内存泄漏。

On the other hand, the similar admonition to close your files on exit has a much more concrete result - if you don't, the data you wrote to them might not get flushed, or if they're a temp file, they might not get deleted when you're done. Also, database handles should have their transactions committed and then closed when you're done with them. Similarly, if you're using an object oriented language like C++ or Objective C, not freeing an object when you're done with it will mean the destructor will never get called, and any resources the class is responsible might not get cleaned up.

您是正确的,当进程退出时,内存将自动释放。有些人在进程终止时尽量不进行广泛的清理,因为它将全部移交给操作系统。然而,当你的程序运行时,你应该释放未使用的内存。如果不这样做,如果您的工作集太大,最终可能会耗尽或导致过度分页。