它是很好的做法,以释放在C中的NULL指针? [英] Is it good practice to free a NULL pointer in C?

查看:117
本文介绍了它是很好的做法,以释放在C中的NULL指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  是否免费(PTR)其中PTR为NULL损坏内存?


我正在写释放的指针,如果它是的malloc()版的C函数。指针可以是NULL(在发生错误和code没有得到任何分配机会的情况下)或分配的malloc()。是安全的使用免费(PTR); 而不是如果(PTR!= NULL)免费(PTR);

GCC 不抱怨可言,甚至与 -Wall -Wextra -ansi -pedantic ,但它好的做法呢?


解决方案

从的ISO-IEC 9899

 无效免费(无效* PTR);


  

如果 PTR 是一个空指针时,没有采取行动。


不检查 NULL ,它只是增加了更多的虚拟code阅读,因此是一个不好的做法。


但是,必须的总是使用时,检查 NULL 指针的malloc &安培;合。在这种情况下, NULL 意味着出事了,很有可能是没有内存可用。

Possible Duplicate:
Does free(ptr) where ptr is NULL corrupt memory?

I'm writing a C function that frees a pointer if it was malloc()ed. The pointer can either be NULL (in the case that an error occured and the code didn't get the chance to allocate anything) or allocated with malloc(). Is it safe to use free(ptr); instead of if (ptr != NULL) free(ptr);?

gcc doesn't complain at all, even with -Wall -Wextra -ansi -pedantic, but is it good practice?

解决方案

Quoting the C standard, 7.20.3.2/2 from ISO-IEC 9899:

void free(void *ptr);

If ptr is a null pointer, no action occurs.

Don't check for NULL, it only adds more dummy code to read and is thus a bad practice.


However, you must always check for NULL pointers when using malloc & co. In that case NULL mean that something went wrong, most likely that no memory was available.

这篇关于它是很好的做法,以释放在C中的NULL指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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