https://www.geeksforgeeks.org/void-pointer-c-cpp/?ref=lbp
悬空指针
一个指针指向的内存已经被释放(或删除)了,那么这个指针被称为悬空指针。
三种不同情况
已经被释放的内存
// Deallocating a memory pointed by ptr causes// dangling pointer#include <stdlib.h>#include <stdio.h>int main(){int *ptr = (int *)malloc(sizeof(int));// After below free call, ptr becomes a// dangling pointerfree(ptr);// No more a dangling pointerptr = NULL;}
函数调用
// The pointer pointing to local variable becomes
// dangling when local variable is not static.
#include<stdio.h>
int *fun()
{
// x is local variable and goes out of
// scope after an execution of fun() is
// over.
int x = 5;
return &x;
}
// Driver Code
int main()
{
int *p = fun();
fflush(stdin);
// p points to something which is not
// valid anymore
printf("%d", *p);
return 0;
}
//输出垃圾地址
//如果p为静态变量,则不会出现悬空问题
// The pointer pointing to local variable doesn't
// become dangling when local variable is static.
#include<stdio.h>
int *fun()
{
// x now has scope throughout the program
static int x = 5;
return &x;
}
int main()
{
int *p = fun();
fflush(stdin);
// Not a dangling pointer as it points
// to static variable.
printf("%d",*p);
}
指针越界
void main()
{
int *ptr;
.....
.....
{
int ch;
ptr = &ch;
}
.....
// Here ptr is dangling pointer
}
void指针
void指针是特定的指针类型, 指向存储在存储中的某些数据位置的指针, 特别的是它还没有指定数据类型。 void 也是一种数据类型, 可以理解为最基本的数据类型,指向的数据可以是任何类型。类似与java python中的 object 类。是万物之源
如果我们将Char数据类型的地址分配给void指针,它将成为char指针.
任何指针类型都可转换为void指针,因此它可以指向任何值。
重要的点:
- void 指针是不能被引用的,但是它可以被转化成其他类型的指针来引用
- 由于缺乏具体的值(数据宽度:如果是int 则指针+1 ,地址+4。如果是char,指针+1,地址加1),因此在void的指针上不可能进行指针算术。
#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;
//A void pointer
void *ptr;
ptr = &x;
// (int*)ptr - does type casting of void
// *((int*)ptr) dereferences the typecasted
// void pointer variable.
printf("Integer variable is = %d", *( (int*) ptr) );
// void pointer is now float
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );
return 0;
}
null 指针
null指针是指向什么都没有的内存 (不太严谨,以后补回来)。如果我们没有将地址分配给指针,那么我们只需使用null就行了。
#include <stdio.h>
int main()
{
// Null Pointer
int *ptr = NULL;
printf("The value of ptr is %p", ptr);
return 0;
}
//The value of ptr is (nil)
Important Points:
- NULL 指针 vs 未初始化的指针-一个未初始化的指针存储一个未定义(随机)的值。一个空指针存储了一个定义的值,但这个值被环境(系统)定义为不是任何成员或对象的有效地址。
- NULL vs Void Pointer- null 指针是一个值,void pointer 是一种类型
野指针
一个没有被初始化为任何东西(甚至不是NULL)的指针被称为野指针。指针可能被初始化为一个非NULL的垃圾值(随机值),但它可能不是一个有效的地址。
int main()
{
int *p; /* wild pointer */
int x = 10;
// p is not a wild pointer now
p = &x;
return 0;
}
