概念: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
链接:点击打开链接