当一个程序终止使用不是免费的malloc分配的内存时会发生什么?

San*_*raj 16 c malloc free valgrind memory-leaks

说我有以下程序

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    int * i;

    if ((i = malloc(sizeof(int) * 100)) == NULL) {
        printf("EROOR: unable to allocate memory \n");
        return -1;
    }

    /* memory is allocated successfully */

    /* memory is not free'ed but program terminates */
    // free(i);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的程序调用malloc分配一些内存而不调用free取消分配它.程序终止而不取消分配内存.

Valgrind清楚地发现内存泄漏.

<snap>
==14209== HEAP SUMMARY:
==14209==     in use at exit: 400 bytes in 1 blocks
==14209==   total heap usage: 1 allocs, 0 frees, 400 bytes allocated
==14209== 
<sanp>
==14209== LEAK SUMMARY:
==14209==    definitely lost: 400 bytes in 1 blocks
==14209==    indirectly lost: 0 bytes in 0 blocks
==14209==      possibly lost: 0 bytes in 0 blocks
==14209==    still reachable: 0 bytes in 0 blocks
==14209==         suppressed: 0 bytes in 0 blocks
==14209== 
==14209== For counts of detected and suppressed errors, rerun with: -v
==14209== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Run Code Online (Sandbox Code Playgroud)

题:

当程序终止时,分配的内存会发生什么但不是free'd?

更新:考虑这个代码是在不同的操作系统上执行的 - 比如windows,linux,solarix,macos等.这个代码在终止期间的行为有什么不同吗?

Tim*_*nes 14

其他答案告诉你两个重要的事情:

  1. 是的,操作系统会回收内存,因此您在技术上并不需要free()它.
  2. 无论如何,释放你所提出的所有内容都是一种很好的做法.

但是,重要的是要说明为什么free()你所做的每一件事都是好的做法.在我看来:

  1. 习惯:如果您在释放只要您malloced的习惯得到的,你不会不小心当存储段不在身边的程序的生命周期忘记.
  2. 可维护性: 如果有人来重构您的程序,以便在程序的生命周期内不再存在一段内存,原始中清理代码的存在意味着重构版本很可能还包含清理代码.对我来说,这是最重要的原因.
  3. 调试:如果我们希望所有内存都能正确清理,那么发现实际泄漏的内存要容易得多.


Don*_*sto 7

操作系统将回收未释放的内存.

但是释放所有分配的内存是一个很好的做法 malloc