c - 当程序终止时,使用未释放的 malloc 分配的内存会发生什么情况?

标签 c memory-leaks malloc free valgrind

假设我有以下程序

#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;
}

上面的程序调用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)

问题:

当程序终止时,分配但未释放的内存会发生什么?

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

最佳答案

其他答案告诉您两件重要的事情:

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

但是,重要的是要说明为什么 free() 您分配的所有内容是一种很好的做法。在我看来:

  1. 习惯:如果您养成每次 malloc 时都释放的习惯,您就不会在程序的整个生命周期中不小心忘记某个内存段。
  2. 可维护性:如果有人来重构您的程序,以便一段内存在程序的生命周期内不再存在,那么原始清理代码的存在将意味着它非常重构版本可能还包含清理代码。对我来说,这是最重要的原因。
  3. 调试:如果我们期望正确清理所有内存,那么发现实际上泄漏的内存会容易得多。

关于c - 当程序终止时,使用未释放的 malloc 分配的内存会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10223677/

相关文章:

c - glib 内存分配 VS std *alloc 和 free

c++ - Malloc vs New for Primitives

java - 设置antlr ide和antlr包

memory-leaks - 使用pytest进行pyqt测试中的内存泄漏

c - 当遇到 exit(1) 时,malloc 的内存会发生什么情况?

Perl XS : create and return array of strings (char*) taken from calling a C function or undef on failure

php - 是否有用于 PHP 的 CURLOPT_RETURNTRANSFER 的 C API?

c++ - 在 C 中 Hook 制表符补全

c - 字符数组的状态

c - 如果在使用 malloc 后它返回一个 NULL 指针并且您继续尝试使用该指针,会发生什么情况?