【发布时间】:2014-10-29 08:01:38
【问题描述】:
我对野指针和悬空指针的一些细节感到困惑,这是我的代码:
#include <iostream>
using std::cout;
using std::endl;
class A
{
public:
void Func() { cout << "Func of class A, the address is:" << this <<endl; }
};
void Test(void)
{
A *p;
//get an error in VS2013 because of uninitialized pointer.
//But it's ok in g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
p->Func(); // wild pointer, ((1))
{
A a;
p = &a;
p->Func();
}
p->Func(); //dangling pointer ((2))
}
int main()
{
Test();
return 0;
}
结果如下:
窗户:Func of class A, the address is:003CFD47
Func of class A, the address is:003CFD47
Ubuntu:Func of class A, the address is:0xb74ef39d
Func of class A, the address is:0xbff85a3b
Func of class A, the address is:0xbff85a3b
我的问题:
(1) g++ 编译器让 wile 指针在 ((1)) 处传递,即使在运行代码时,它似乎也指向“某个对象”。为什么会发生这种情况?是编译器的bug吗?
(2) 据我所知,在分块语句之后,p 将是 ((2)) 处的悬空指针。但是为什么 p 可以继续指向 Func() 呢?因为对象a占用的空间没有被其他应用程序覆盖?
【问题讨论】:
-
这是未定义的行为。
-
哪个是?悬空指针?@πάνταῥεῖ
-
@wjk 访问/取消引用它。
-
但是这里的 p 在开始时没有初始化。一些帮助,我会看看它。谢谢。@AntonSavin
-
那么既然它是未定义的,编译器可以做任何事情吗?@πάνταῥεῖ