一个电话可以自由(c)中曾经失败? [英] Can a call to free() in C ever fail?

查看:184
本文介绍了一个电话可以自由(c)中曾经失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将呼叫免费()以任何方式失败了?

例如:

 免费(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 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)中曾经失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆