相关疑难解决方法(0)

悬空指针,free()后价值变化的原因?

在下面的代码段中free(x),为什么会y变为0?

根据我的理解,堆中被指向x并且仍然被指向的内存y尚未分配给其他人,那么如何将其更改为0?

此外,我认为不会free(x)将其改为0.

任何意见?

#include <stdio.h>

int main(int argc, char *argv[])
{
    int *y = NULL;
    int *x = NULL;

    x = malloc(4);
    *x = 5;

    y = x;
    printf("[%d]\n", *y); //prints 5

    free(x);

    printf("[%d]\n", *y); //why doesn't print 5?, prints 0 instead

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c pointers dangling-pointer

3
推荐指数
1
解决办法
1231
查看次数

标签 统计

c ×1

dangling-pointer ×1

pointers ×1