野指针分类
int *p;
cout << "p = "<<p <<" *p = "<<(*p)<<endl;
- 指针指向了动态分配的内存,在内存被释放后,指针不会置空,但是指针的指向已经失效
int *p = new int(3);
cout << "p = "<<p <<" *p = "<<(*p)<<endl;
delete p;
cout << "p = "<<p <<" *p = "<<(*p)<<endl;
image.png
#include <iostream>
#include<string>
using namespace std;
int* fun() {
int a = 3;
cout << "a = "<<a <<" &a = "<<&a<<endl;
return &a;
}
int main() {
int *p = fun();
cout << "p = "<<p <<" *p = "<<(*p)<<endl;
return 0;
}
image.png
规避野指针
- 指针在定义的时候,如果么有指向,就初始化nulptr
- 动态内存被释放后,将其置为nullptr
- 函数不要返回局部变量的地址
网友评论