一个电话可以自由(c)中曾经失败? [英] Can a call to free() in C ever fail?
问题描述
可以将呼叫免费()
以任何方式失败了?
例如:
免费(NULL);
舷NULL指针不能失败。和免费
不会返回任何错误,但释放未分配的内存,已经释放的内存或分配块的中间是未定义的行为 - 这可能导致内存错误,程序可能会中止(或更糟的是,它会破坏堆结构和系统崩溃后)。
或者,甚至比这更糟的是,保持运行,但完全破坏你的数据,并将其写入到磁盘,没有你实现: - )
标准(C99)的相关部分章节<code> 7.20.3.2 :
的#include&LT;&stdlib.h中GT;
结果
无效免费(无效* PTR);
的
免费
功能使空间指向PTR
被释放,也就是进一步提供分配。如果PTR
是一个空指针时,没有采取行动。否则,如果该参数不匹配的释放calloc
,的malloc
或的realloc
函数,或者如果空间已释放通过调用免费
或的realloc
,该行为是不确定的。
的
免费
函数返回值。
块引用>Can a call to
free()
fail in any way?For example:
free(NULL);
解决方案Freeing a NULL pointer cannot fail. And
free
doesn't return any error, but freeing unallocated memory, already freed memory or the middle of an allocated block is undefined behaviour - it may cause a memory error and the program may abort (or worse, it will corrupt the heap structure and crash later).Or, even worse than that, keep running but totally corrupt your data and write it to disk without you realising :-)
The relevant portion of the standard (C99) is section
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)中曾经失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!