问题
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.
回答1:
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.
回答2:
You release neither node1
nor node2
. You release the memory they point to.
With that in mind, it should become clear why you should only call free
once
回答3:
You should pass the address returned by malloc()
and family to free()
in-order to free the allocated memory.
In your case you are just assigning the returned address to some other pointer and using that in free which is fine.
You shouldn't do
node2 = node1;
node2 = node2 +1;
free(node2);
So you can use one of them in your case to free the memory
free(node1)
and free(node2)
are same in your case
回答4:
node1
is a pointer, meaning the value of it is the virtual memory address of the allocated struct.
Assigning node2 = node1
just copies that address.
As a result free(node1)
and free(node2)
are equivalent.
来源:https://stackoverflow.com/questions/40760341/c-language-releasing-memory-of-pointers-to-struct