动态内存分配“删除”
如果我为 int
对象动态分配内存位置,如下所示:
int *x = new int;
完成后,想要释放堆上的内存,我将执行以下操作:
delete x;
现在,如果我不执行以下操作:
x = NULL;
将会 x< /code> 指向另一个地址? 更新:
另一个
而不是许多
说我没有做x = NULL
并做了另一个< /strong> 删除x;
,会发生什么?
If I allocated a memory location for an int
object dynamically as follows:
int *x = new int;
After done with it, and want to free the memory on the heap, I will do the following:
delete x;
Now, if I did not do the following:
x = NULL;
Will x
be pointing to another address? UPDATE: another
instead of many
Say I didn't do x = NULL
and made another delete x;
, what will happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
= NULL
- 在我看来,这是不好的做法)都是未定义的。https://isocpp.org/wiki/faq/freestore-mgmt
x
(apart from= NULL
- which is, imo, bad practice) after you delete it is undefined.https://isocpp.org/wiki/faq/freestore-mgmt
在
删除
之后,指针通常仍包含(现在空闲)内存的地址。第二个delete
给出了未定义的行为,所以不要这样做。After the
delete
, the pointer will typically still contain the address of the (now free) memory. The seconddelete
gives undefined behavior, so don't do that.它将调用未定义的行为。如果您不执行
x=NULL
,则x
将指向无效的内存位置,如果您尝试使用该位置,将导致未定义的行为。It will invoke undefined behavior. If you don't do
x=NULL
thenx
will be pointing to an invalid memory location which if you try to use will cause undefined behavior.类型:
结果:
0x8e19008
0x8e19008
** glibc 检测到 ** ./a.out:双重释放或损坏(fasttop):0x08e19008 *
如您所见,地址保持不变,但第二次删除结束在运行时错误中。行为在细节上可能取决于环境,但作为一般规则,它是行不通的。
type:
result:
0x8e19008
0x8e19008
** glibc detected ** ./a.out: double free or corruption (fasttop): 0x08e19008 *
as you see, the address stays the same, but the second delete ends in a runtime error. behaviour may in detail depend on environment, but as a general rule it will not work.
对已删除的内存调用删除将导致未定义的行为。一般来说,你的程序会崩溃。
删除 x 后,它将指向“编译器相关”。大多数编译器只会让它指向调用删除之前的位置。但该内存地址不再有效,因此不应被调用。
出于同样的原因,如果需要的话,必须非常明智和谨慎地使用“删除此”。 :-)
calling delete on already deleted memory will cause undefined behaviour. Generally, your program will crash.
After deleting x, where it will be pointing is "compiler dependent". Most of the compilers will just let it point to where it was, before delete was called. But that memory address is no more valid, and hence should not be called.
For this same reason, "delete this" must be used very judiciously and carefully, if at all needed. :-)
第二次删除未定义。
附带说明一下,有一些工具可以检测双重删除。最好的之一是 Valgrind。
The secondth delete is undefined.
As a side note, there are tools to detect a double deletion. One of the best one around is Valgrind.