在 C 中释放 NULL 指针是一种好习惯吗? [英] Is it good practice to free a NULL pointer in C?

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

问题描述

<块引用>

可能的重复:
是否 free(ptr) where ptr is NULL 损坏内存?

我正在编写一个 C 函数,如果它被 malloc() 编辑,它会释放一个指针.指针可以是 NULL(在发生错误并且代码没有机会分配任何东西的情况下)或用 malloc() 分配.使用 free(ptr); 而不是 if (ptr != NULL) free(ptr); 是否安全?

gcc 根本没有抱怨,即使使用 -Wall -Wextra -ansi -pedantic,但这是好的做法吗?

解决方案

引用 C 标准,7.20.3.2/2 from ISO-IEC 9899:

void free(void *ptr);

<块引用>

如果 ptr 是空指针,则不会发生任何动作.

不要检查NULL,它只会添加更多的伪代码来读取,因此是一种不好的做法.

<小时>

但是,在使用 malloc 时,您必须始终检查 NULL 指针公司在这种情况下,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天全站免登陆