8.5 迷途指针(空指针或再分配)

Posted: March 26, 2011 in C++

/*
迷途指针(stray pointer)(wild pointer)(dangling pointer):
这是将delete用于指针(释放内存),但没有将它设置为空指针,引发的.
对于已经delete的指针,就避免再次使用它,虽然这个指针仍旧指向原来的内存区域,
但是编译器可能已经将其他数据储存在这里.
不重新赋值就再次使用它很容易导致系统崩溃.
更糟糕的是,程序表面上运行,但是过不多久,就崩溃了.
所以,安全起见,删除指针后,把其设置为空(0),解除”武装”.
*/

#include <iostream>

using namespace std;

void main()
{
         unsigned short int *p1=new unsigned short int;
         *p1=5;
         cout<<*p1<<endl;
         delete p1;

         long *p2=new long;
         *p2=2000000;
         cout<<*p2<<endl;
 
         /*这里如果重新分配区域就会避免发生迷途指针:
         即:(再分配)
         p1=new unsigned short int;*/
 
         *p1=10;
         cout<<*p1<<endl;
         cout<<*p2<<endl;//未修改p2的前提下,输出结果发生改变.
}

未分配:

 

再分配:

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s