我为什么要释放()由malloc()分配的对象?

问题描述 投票:1回答:1

一直被告知要释放malloc()分配的堆内存:

#include <stdlib.h>

#define width 5

int main(void)
{
    char* ptr = malloc(sizeof(*ptr) * width);

    /* some stuff with the heap object */

    free(ptr);

    return 0;
}

但是现在我不需要读What REALLY happens when you don't free after malloc?,因为在程序终止后,操作系统会自动释放占用的内存。

但是为什么我的老师告诉我这样做?这样做有什么好处吗?

c memory-management malloc heap-memory free
1个回答
1
投票

在您的示例中,这没有关系,因为正如您所说,当程序退出时,操作系统将为您清理。

© www.soinside.com 2019 - 2024. All rights reserved.