c++野指针
2022-11-07 本文已影响0人
arkliu
野指针分类
- 指针定义的时候,没有进行初始化
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
- 函数不要返回局部变量的地址