C语言:释放指向struct的指针的内存 [英] C language: Releasing memory of pointers to struct

查看:234
本文介绍了C语言:释放指向struct的指针的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我已经声明了一个指向结构的指针,并使用此定义将其分配给malloc()

Say I have declared a pointer to a struct and assign it with malloc() using this definition

typedef struct node {
    int info;
    struct node *next;
} NODE;

然后在代码中的某个地方我声明了两个指向它的指针

Then somewhere in the code I declared two pointers to it

NODE *node1, *node2 = NULL;

node1 = malloc(sizeof(NODE));
node2 = node1;

我的问题是,是否应该像人们总是通过 free(node1)对node1一样使用"free()"来释放node2.分配 node2 = node1;

My question, should I use "free()" to release node2 just like people always do to node1 via free(node1). What's exactly the effect of the assignment node2 = node1;

谢谢.

推荐答案

执行时

node1 = malloc(sizeof(NODE));

你有类似的东西


+-------+      +-----------------------------+
| node1 | ---> | memory for a NODE structure |
+-------+      +-----------------------------+

在分配了node2 = node1之后,您有了:

After the assignment node2 = node1 you have instead this:


+-------+
| node1 | -\
+-------+   \    +-----------------------------+
             >-> | memory for a NODE structure |
+-------+   /    +-----------------------------+
| node2 | -/
+-------+

换句话说,您有两个指针指向相同内存.

In other words you have two pointers pointing to the same memory.

尝试使用两个指针变量之一调用free会使两个指针无效.

Attempting to call free using either of the two pointer variable will invalidate both pointers.

这篇关于C语言:释放指向struct的指针的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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