C / C ++中的悬空指针,空指针,空指针和野生指针
悬空指针
悬空指针是指向已释放(或删除)的内存位置的指针。指针有多种悬挂指针的方式
函数调用
当局部变量不是静态的时,指向局部变量的指针将悬空。
int *show(void) {
int n = 76; /* ... */ return &n;
}输出结果
Output of this program will be garbage address.
内存分配
#include <stdlib.h> #include <stdio.h> int main() {
float *p = (float *)malloc(sizeof(float));
//动态内存分配。free(p);
//after calling free() p becomes a dangling pointer p = NULL;
//现在,p不再是悬空的指针。
}变量超出范围
int main() {
int *p //一些代码// {
int c; p=&c;
}
//一些代码//
//p在这里悬空指针。
}空指针
C中的空指针是一个不与任何数据类型相关联的指针。它指向存储中的某些数据位置,意味着指向变量的地址。也称为通用指针。
它有一些局限性
空指针由于其具体大小而无法进行指针算术运算。
不能用作取消引用。
这是一个简单的例子
#include<stdlib.h>
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
printf("Integer variable is = %d", *( (int*) p) );
p = &b;
printf("\nFloat variable is = %f", *( (float*) p) );
return 0;
}输出结果
Integer variable is = 7 Float variable is = 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指针传递给函数参数。
在访问任何指针变量之前检查空指针。这样,我们就可以在与指针相关的代码中执行错误处理,例如,仅当其不为NULL时才取消引用指针变量。
示例
#include<iostream>
#include <stdio.h>
int main() {
int *p= NULL;//initialize the pointer as null.
printf("The value of pointer is %u",p);
return 0;
}输出结果
The value of pointer is 0.
野指针
通配指针是指向任意内存位置的指针。(甚至不是NULL)
int main() {
int *ptr; //wild pointer
*ptr = 5;
}