我总是被告知要释放 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?我不需要这样做,因为操作系统会在程序终止后自动释放占用的内存。
但是为什么我的老师要我这么做呢?这样做有什么好处吗?
最佳答案
But why did my teacher told me to do so then? Is there any benefit of doing so?
考虑一下,如果您的程序是一个长时间运行的进程(例如数据库服务器),并且在其内部的某个位置有一个函数不断分配内存(例如,每次处理查询时),会发生什么情况?永远不会释放它。或者,更普通的是,桌面应用程序(例如文字处理器)您希望在处理某事时保持运行。
是的,操作系统会在进程终止后释放其使用的所有资源。但许多程序都不是短命的。
关于c - 为什么我要 free() 一个由 malloc() 分配的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59917863/