我感到困惑野指针和野指针的一些细节,这里是我的代码:为什么悬挂指针可以继续访问对象?
#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;
}
结果就像如下:
的Windows:
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 ++编译器让wil在((1))处传递e指针,即使运行代码,它似乎指向'某个对象'。为什么会这样呢?它是编译器的错误吗? (2)据我所知,在块句之后,p将是((2))处的悬挂指针。但为什么可以继续指向Func()?由于对象a占用的空间不会被其他应用程序覆盖吗?
这是不确定的行为。 – 2014-10-29 08:02:44
这是?悬挂指针?@πάνταῥεῖ – kkwang 2014-10-29 08:03:34
@wjk访问/取消引用它。 – 2014-10-29 08:04:13