吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → 悬空指针、void指针、空指针和野指针

悬空指针、void指针、空指针和野指针

来源:网络 | 更新时间:2022-01-16 19:40:41

悬空指针

指向已被删除(或释放)的内存位置的指针称为悬空指针。Pointer 作为悬空指针的三种不同方式
  • 内存的释放
// 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 pointer
free(ptr); 

// No more a dangling pointer
ptr = 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;
}
输出:
A garbage Address
如果 x 是静态变量,则不会出现上述问题(或 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);
}
输出:
5
  • 变量超出范围
void main()
{
int *ptr;
.....
.....
{
int ch;
ptr = &ch;
} 
..... 
// Here ptr is dangling pointer
}

void指针

void 指针是一种特定的指针类型 – void * – 指向存储中某个数据位置的指针,它没有任何特定类型。void 是指类型。基本上它指向的数据类型可以是任何类型。如果我们将 char 数据类型的地址分配给 void 指针,它将成为 char 指针,如果是 int 数据类型,则将成为 int 指针,依此类推。任何指针类型都可以转换为 void 指针,因此它可以指向任何值。 要点
  1. void 指针不能被取消引用。然而,它可以使用类型转换 void 指针来完成
  2. 由于缺乏具体值和大小,指针算术在 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;
}
输出:
Integer variable is = 4
Float variable is= 5.500000

空指针

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)
要点
  1. NULL 与未初始化的指针——未初始化的指针存储未定义的值。空指针存储一个已定义的值,但该值由环境定义为不是任何成员或对象的有效地址。
  2. NULL vs Void Pointer – Null 指针是一个值,而 void 指针是一个类型
 

野指针

尚未初始化为任何内容(甚至不是 NULL)的指针称为野指针。指针可能被初始化为可能不是有效地址的非 NULL 垃圾值。
int main()
{
int *p; /* wild pointer */

int x = 10;

// p is not a wild pointer now
p = &x;

return 0;
}
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com