何时释放 C 代码中的内存?

nou*_*r02 4 c memory malloc calloc

例如,当我在 while 循环外分配内存时,可以在其中释放它吗?这两个代码等价吗?

int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
  memory=10;
  free(memory);
}


int* memory = NULL;
memory = malloc(sizeof(int));
if (memory != NULL)
{
  memory=10;
}
free(memory);
Run Code Online (Sandbox Code Playgroud)

ale*_*rus 5

是的,它们是等价的。free()如果分配没有成功,您不必调用。
请注意,这memory是指向的指针int,您必须取消引用它才能将某些内容分配给它的内存块;

int* memory = NULL;
memory = malloc(sizeof(int));
if (memory)
    *memory=10;
free(memory);
memory = NULL;
Run Code Online (Sandbox Code Playgroud)