空指针
当给空指针所指的地址赋值时,会报错
int *p=nullptr;
*p=10;
野指针
-
- 指针没有被初始化 随机一个值 (声明时候初始化 P=NULL)
int *p;//野指针,未初始化
-
- 指针p被free或者delete后没有置为NULL
int *p=new int;
delete p; //删除后不知道p指向哪里
#include <iostream>
using namespace std;
class A
{
public:
void Func(void);
};
void A::Func(void)
{
cout << "Func of class A" << endl;
}
void Test(void)
{
A *p;
{
A a;
p = &a;
}
p->Func(); //应该出错, a对象已经消失,p为野指针
}
int main()
{
Test();
int *p;
{
int s = 3; //局部变量
p = &s;
}
//cout << s << endl; s已经不存在了
*p = 10; //应该出错, 地址非法
cout << p << endl;
cout << *p << endl;
/*但是编译器不讲道理啊, 编译运行都是对了, 有不对的吗? */
return 0;
}
-
- 指针操作超越了变量的作用范围