调用 free()
是否会以任何方式失败?
例如:
free(NULL);
最佳答案
释放 NULL 指针不会失败。和 free
不返回任何错误,但释放未分配的内存、已释放的内存或分配 block 的中间是未定义的行为 - 它可能导致内存错误并且程序可能中止(或者更糟的是,它会破坏堆结构并稍后崩溃).
或者,更糟糕的是,继续运行但完全损坏您的数据并在您没有意识到的情况下将其写入磁盘:-)
标准 (C99) 的相关部分是 7.20.3.2
节:
#include <stdlib.h>
void free(void *ptr);
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by thecalloc
,malloc
, orrealloc
function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined.The
free
function returns no value.
关于在 C 中调用 free() 会失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5308758/