在 C 中调用 free() 会失败吗?

标签 c memory-management free

调用 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 by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

The free function returns no value.

关于在 C 中调用 free() 会失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5308758/

相关文章:

c - 确定给定用户内存大小和偏移量的所有可能的 32KB block 数

c - 降低 GTK+ 中的按钮高度

c++ - 在 C++ 中转置大文件的最有效内存方式

c - 使用 free() 函数的问题

c - 使用 free() 时为 "Heap corruption detected"

c - OpenGL VBO 孤立实现

c - 将结构传递给函数

c - 以下 C 代码中的内存泄漏

c - 一旦超出范围,C 是否会重用本地 block var 的内存?

c - 我需要释放局部变量吗?