问题描述
在下面的代码中,为什么指针 x
保存的地址在 delete
后改变?据我理解, delete
调用应该释放从堆分配的内存,但不应该更改指针地址。
In the following code, why is the address held by pointer x
changing after the delete
? As I understand, the delete
call should free up allocated memory from heap, but it shouldn't change the pointer address.
using namespace std;
#include <iostream>
#include <cstdlib>
int main()
{
int* x = new int;
*x = 2;
cout << x << endl << *x << endl ;
delete x;
cout << x << endl;
system("Pause");
return 0;
}
OUTPUT:
01103ED8
2
00008123
观察:我使用Visual Studio 2013和Windows 8.据报告,这不工作在其他编译器相同。此外,我明白这是坏的做法,我应该重新分配指针为NULL,删除后,我只是想了解是什么驱动这种奇怪的行为。
Observations: I'm using Visual Studio 2013 and Windows 8. Reportedly this doesn't work the same in other compilers. Also, I understand this is bad practice and that I should just reassign the pointer to NULL after it's deletion, I'm simply trying to understand what is driving this weird behaviour.
推荐答案
好吧,为什么不呢?这是完全合法的输出 - 读取指针后删除它导致未定义的行为。这包括指针的值改变。 (实际上,这甚至不需要UB; delete
d指针可以指向任何地方。)
Well, why not? It's perfectly legal output -- reading a pointer after having deleted it leads to undefined behavior. And that includes the pointer's value changing. (In fact, that doesn't even need UB; a delete
d pointer can really point anywhere.)
这篇关于指针被删除后,指针变化时保存的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!