c - Why free() release data but save next_node value? -
i training lists , point start wonder how work free() function. think clear either data , next_node values in struct first_node (look @ code), instead data values destroy , next_node still point next position on list. why?
struct data { int a; int b; }; struct node { struct data* data; struct node* next_node; }; struct list { struct node* first_node; }; void init(struct list* list) { list->first_node = null; } … struct data* remove_first_element_from_list(struct list* list) { if (list->first_node == null) { printf("the list empty!\n"); return 0; } struct data *pointer; pointer = list->first_node->data; free(list->first_node); list->first_node = list->first_node->next_node; return pointer; }
thanks explaination.
you have undefined behavior when do
list->first_node = list->first_node->next_node
the ub because list->first_node
no longer points allocated memory.
however, nothing says when call free
data has cleared or otherwise modified. tell operating system memory once again available allocate. that's why can still use pointer, , that's 1 of things ub, behavior undefined, , can seem work when in reality it's serious problem.
Comments
Post a Comment