为什么用 free() 释放内存后要使指针无效?
可能的重复:
真的应该将指针设置为NULL 释放它们后?
我已经使用 malloc 和 calloc 为指针分配了动态内存。使用此指针后,我应该释放内存,以便该块可以返回到操作系统(很好)。现在我的问题是,释放块后,为什么我应该做这样的事情:
pointer = NULL;
感谢帮助......
Possible Duplicate:
Should one really set pointers toNULL
after freeing them?
I have allocated dynamic memory to pointer using malloc and calloc. After using this pointer, I should free the memory so that block can be returned to OS(its fine). Now My question is that after freeing the block, why should I do something like that:
pointer = NULL;
Thanks for help...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这样我们就不会留下悬空指针。如果不清空未使用的指针,您将无法在以后检测该指针是否可以安全地取消引用或释放。并且尝试取消引用或释放悬空指针会导致未定义的行为(=崩溃)。
So that we don't leave dangling pointers behind. Without nulling out unused pointers, you have no way to detect later whether the pointer can be safely dereferenced or freed. And attempting to dereference or free a dangling pointer results in undefined behaviour ( = crash).
因为如果您再次尝试free(),就会发生
未定义行为
。另请注意,在
free
之后,内存将被程序回收。不是操作系统。程序执行结束后,内存由操作系统回收。Because if you try to
free()
it againUndefined Behaviour
will occur.Also, note that after
free
-ing, the memory is reclaimed by the program. not the OS. The memory is reclaimed by the OS, after the execution of the program has ended.如果指针变量保留在范围内,您以后将无法确定它是否存储了有效地址,并且如果您尝试使用该指针,则会遇到未定义的行为。
在
free()
之后将指针设置为null是一种保护措施。如果您知道指针在free()
之后不久就会超出范围,则不需要这样做:但同时大多数编译器会发现,在这种情况下,将指针设置为 null 不会产生任何影响。可观察到的效果并优化该代码。
If the pointer variable remains in scope you can't later find whether it stores a valid address or not and if you try to use that pointer you run into undefined behavior.
Setting a pointer to null after
free()
is a protection measure. You don't need this if you know that the pointer will get out of scope soon afterfree()
:but at the same time most compilers will see that in such case setting a pointer to null has no observable effect and optimize that code away.
这样做更好是因为:
首先,它使您的代码更简单。当您管理内存时,您会花费大量时间进行
malloc
和free
。如果将其设置为 NULL,您可以执行以下操作:这真的更容易,不是吗?
其次,在调试器中发现 NULL (0) 指针也比悬挂指针更容易。当你在调试器中看到
0x0
时,很容易猜测存在指针管理问题。当你看到0xbac765
时,就更难了:)my2c
It is better because :
First, it makes your code simpler. When you manage memory, you do
malloc
andfree
a lot of time. If you set it to NULL you can do things like :It's really easier, no ?
Second, it is easier too to spot a NULL (0) pointer in the debugger than a dangled one. It easy to guess that there is a pointer management problem when you see
0x0
in the debugger.When you see0xbac765
, it's harder :)my2c