C++ 中的悬空指针、空指针、空指针和野指针
悬空指针
悬空指针是指向已被释放(或删除)的内存位置的指针。指针充当悬空指针的方式有很多种。
函数调用
当局部变量不是静态时,指向局部变量的指针在局部变量超出作用域时会变成悬空指针。
int *show(void) {
int n = 76; /* ... */ return &n;
}输出
Output of this program will be garbage address.
内存的释放
int main() {
float *p = (float *)malloc(sizeof(float));
//dynamic memory allocation.
free(p);
//after calling free()
p becomes a dangling pointer p = NULL;
//now p no more a dangling pointer.
}变量超出作用域
int main() {
int *p //some code// {
int c; p=&c;
}
//some code//
//p is dangling pointer here.
}空指针
空指针是指与任何数据类型都不关联的指针。它指向存储器中的某个数据位置,即指向变量的地址。它也被称为通用指针。
它有一些限制
- 由于空指针的具体大小,因此无法对其进行指针运算。
- 它不能用作解引用。
示例
#include<stdlib.h>
#include<iostream>
using namespace std;
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
cout<<*( (int*) p)<<endl ;
p = &b;
cout<< *( (float*) p) ;
return 0;
}输出
7 7.600000
算法
Begin Initialize a variable a with integer value and variable b with float value. Declare a void pointer p. (int*)p = type casting of void. p = &b mean void pointer p is now float. (float*)p = type casting of void. Print the value. End.
空指针
空指针是指向任何东西的指针。
空指针的一些用途是
当指针变量尚未分配任何有效内存地址时,初始化指针变量。
如果我们不想传递任何有效内存地址,则将空指针传递给函数参数。
在访问任何指针变量之前检查空指针。这样,我们可以在与指针相关的代码中执行错误处理,例如,仅当指针不为 NULL 时才解引用指针变量。
示例
#include <iostream>
using namespace std;
int main() {
int *p= NULL; //initialize the pointer as null.
cout<<"The value of pointer is ";
cout<<p;
return 0;
}输出
The value of pointer is 0.
野指针
野指针是指向某个任意内存位置的指针。(甚至不是 NULL)
int main() {
int *ptr; //wild pointer
*ptr = 5;
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP