malloc和C语言中的free [英] malloc and free in C

查看:114
本文介绍了malloc和C语言中的free的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有类似的东西

 struct Node *root;
 struct Node *q;

 root = malloc( sizeof(struct Node));
 q = root;
 free(q);

节点q指向释放的节点吗?还是我必须将root传递给free函数?

is the node q is pointing to freed?? or would I have to pass root to the free function?

推荐答案

rootq都具有相同的值,也就是说,它们指向相同的内存位置.调用free(q)之后,它们两个都是悬空指针,因为它们都指向的对象已释放,但它们仍指向该位置.

Both root and q have the same value, that is to say, they point to the same memory location. After the call to free(q), both of them are dangling pointers because the thing they both point to has been freed but they still point to that location.

要取消引用,都将调用未定义的行为.这包括在其中任何一个上调用free.

To de-reference either would invoke undefined behaviour. This includes calling free on either of them.

这篇关于malloc和C语言中的free的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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