免费后的变量设置为NULL [英] Setting variable to NULL after free

查看:140
本文介绍了免费后的变量设置为NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我公司有,说,释放任何内存后,重置变量设置为NULL编码规则。例如...

In my company there is a coding rule that says, after freeing any memory, reset the variable to NULL. For example ...

void some_func () 
{
    int *nPtr;

    nPtr = malloc (100);

    free (nPtr);
    nPtr = NULL;

    return;
}

我觉得,像上面显示的code,设置为NULL的情况下没有任何意义。还是我失去了一些东西?

I feel that, in cases like the code shown above, setting to NULL does not have any meaning. Or am I missing something?

如果有在这种情况下没有意义,我打算把它与质量团队删除此编码规则。请指点。

If there is no meaning in such cases, I am going to take it up with the "quality team" to remove this coding rule. Please advice.

推荐答案

未使用的指针设置为NULL是一个防守风格,防止悬摆指针错误。如果它被释放后访问悬空指针,你可以阅读或覆盖随机内存。如果一个空指针被访问时,你会得到大多数系统立即崩溃,告诉你马上是什么错误。

Setting unused pointers to NULL is a defensive style, protecting against dangling pointer bugs. If a dangling pointer is accessed after it is freed, you may read or overwrite random memory. If a null pointer is accessed, you get an immediate crash on most systems, telling you right away what the error is.

有关局部变量,它可能是一个有点毫无意义,如果它是显而易见的指针没有被释放后,再访问,因此这种风格更适合于数据成员和全局变量。即使对于局部变量,它可能是一个很好的方法,如果功能继续所述存储器被释放之后

For local variables, it may be a little bit pointless if it is "obvious" that the pointer isn't accessed anymore after being freed, so this style is more appropriate for member data and global variables. Even for local variables, it may be a good approach if the function continues after the memory is released.

要完成的风格,你也应该初始化指针为NULL,他们会被分配一个真正的指针值了。

To complete the style, you should also initialize pointers to NULL before they get assigned a true pointer value.

这篇关于免费后的变量设置为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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