【发布时间】:2021-05-30 05:13:23
【问题描述】:
当例如声明一个 malloc 然后检查它是否为 NULL 以查看它是否已正确分配时,如果它为 null,我是否应该释放内存,例如:
int *p;
p = (int *)malloc(sizeof(int));
if (p == NULL)
{
free(p); //Should I free here or will it create an error?
return NULL;
}
【问题讨论】:
-
只是一个旁注:在
p == NULL...free(p);和free(NULL);是等价的(C 通过值传递参数)并且表现良好(它们什么都不做)的情况下。
标签: c memory dynamic-memory-allocation