免费后悬挂指针,之所以价值变动()? [英] dangling pointer, reason for value change after free()?

查看:145
本文介绍了免费后悬挂指针,之所以价值变动()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下code段,经过免费的(X),为什么ÿ变为0?

按我的理解,在堆内存正被指向x和仍在由y指出,尚未分配给别人,所以它怎么能更改为0?

而且,我不认为它是免费的(X),它更改为0。

任何意见?

 的#include<&stdio.h中GT;INT主(INT ARGC,CHAR *的argv [])
{
        INT * Y = NULL;
        INT * X = NULL;        X = malloc的(4);
        * X = 5;        Y = X;
        的printf([%D]。\\ n,* Y); //输出5        免费(X);        的printf([%D]。\\ n,* Y); //为什么不打印5?0打印代替        返回0;
}


解决方案

这是不确定的行为,解释是只是猜测。

我可以推测,也许你正在运行C库的调试版本,并调试版本免费()做零尖区。

In the following code segment, after free(x), why does y becomes 0?

As per my understanding, the memory in the heap that was being pointed to by x, and is still being pointed by y, hasn't been allocated to someone else, so how can it change to 0?

And moreover, I don't think it is free(x) that changed it to 0.

Any comments?

#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;
}

解决方案

This is undefined behavior, explanations are just speculation.

I can speculate that maybe you are running a debug version of the C library, and that the debug version of free() does zero the pointed area.

这篇关于免费后悬挂指针,之所以价值变动()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆