C language: Releasing memory of pointers to struct

后端 未结 4 1626
一整个雨季
一整个雨季 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

    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

提交回复
热议问题