C language: Releasing memory of pointers to struct

后端 未结 4 1622
一整个雨季
一整个雨季 2021-01-20 06:28

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         


        
4条回答
  •  被撕碎了的回忆
    2021-01-20 06:41

    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.

提交回复
热议问题