一直被告知要释放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?,因为在程序终止后,操作系统会自动释放占用的内存。
但是为什么我的老师告诉我这样做?这样做有什么好处吗?
在您的示例中,这没有关系,因为正如您所说,当程序退出时,操作系统将为您清理。