我调用free(),但指针仍然有数据和它的内容没有改变 [英] I call free(), but the pointer still has data and it's content hasn't changed

查看:105
本文介绍了我调用free(),但指针仍然有数据和它的内容没有改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code如下。

我的问题是关于结果。我想知道,为什么调用free(P)后,
对 - > ELEM变为0,但在p> STR仍包含你好?

My question is about the result. I want to understand, why after calling free(p) p->elem turns to '0', but the p->str still contains "hello"?

#define LEN (sizeof(struct node))
typedef struct node
{
       int elem;
       char *str;

}*p_node;
int main(void)
{
    p_node p;
    p=(p_node)malloc(LEN);
    p->elem=99;
    p->str="hello";
    printf("the p->elem:%d\n",p->elem);
    printf("the p->str :%s\n",p->str);
    free(p);
    printf("the p->elem:%d\n",p->elem);
    printf("the p->str :%s\n",p->str);
    return 0;
}

推荐答案

释放内存实际上并不清除指针或指向(除非为了协助这样的调试问题的专门环境记忆 - 从来不靠行为虽然)。释放它指向的内存后使用指针是无效的,是的未定义行为的。它也可能会崩溃,或者导致随机值进行打印。

Freeing memory doesn't actually clear the pointer or the memory it pointed to (except under specialized circumstances meant to assist in debugging problems like this -- never rely on the behavior though). Using a pointer after freeing the memory it pointed to is invalid, and is undefined behavior. It might as well crash, or cause random values to be printed.

此外,在C你应该不投<$ C $的回归C>的malloc

Also, in C you should not cast the return of malloc.

这篇关于我调用free(),但指针仍然有数据和它的内容没有改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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