为什么在“free”之后取消引用 C 指针的值为 0

Vir*_*mar 2 c pointers

下面是代码:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *p;
    p=(int *)malloc(sizeof(int));
    *p=5;
    printf("Before freeing=%p\n",p);
    printf("Value of p=%d\n",*p);
    //making it dangling pointer
    free(p);
    printf("After freeing =%p\n",p);
    printf("Value of p=%d\n",*p);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

下面是输出:

Before freeing=0x1485010
Value of p=5
After freeing =0x1485010
Value of p=0
Run Code Online (Sandbox Code Playgroud)

释放指针后,解引用给出输出“0”(零)。

下面是另一个也给出“0”的代码

include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
p=(int *)malloc(sizeof(int));

printf("Before freeing=%p\n",(void *)p);
printf("Value of p=%d\n",*p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这个我没有释放内存,只是分配了它,它仍然给出 '0' 。是不是每个未初始化指针的默认值都是'0'??

为什么会这样?

bst*_*our 5

不要依赖于此,这是未定义的行为。free()不必将指针设置为零,这正是您当前的实现为您所做的。如果您想 100% 确定,无论您的编译器、平台等如何,请NULL在释放指针后将其设置为。