Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C language: Releasing memory of pointers to struct

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;

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;

Thanks.

like image 647
James Real Avatar asked Dec 19 '22 11:12

James Real


1 Answers

When you do

node1 = malloc(sizeof(NODE));

you have something like

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

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.

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

like image 59
Some programmer dude Avatar answered Dec 28 '22 08:12

Some programmer dude