天天看點

迷途指針

概念:c中的野指針,C++中的迷途指針都是不為NULL的指針,也不是指向常量的指針,而是指向“垃圾”記憶體的指針。垃圾的意思是未知區域、未知記憶體。

示例代碼:

int   main()  
{  
    int *pInt = new int;  
    *pInt=10;
    cout<<pInt<<endl; 
    cout<<"*pInt: "<<*pInt<<endl;  
    delete pInt;   //pInt為迷途指針!
     
    int *pLong = new int;
    cout<<pInt<<endl;  
    cout<<pLong<<endl;
    *pLong=90000;  
    cout<<"*pLong: "<<*pLong<<endl;  
     
    *pInt=20;      //再次使用pInt! 
     
    cout<<"*pInt: "<<*pInt<<endl;  
    cout<<"*pLong: "<<*pLong<<endl;  
    delete   pLong;  
    return   0;  
}
           

解決方法:避免的方式是在delete pInt的後面加上pInt = NULL

連結:點選打開連結