Freeing memory in a function vs in the same scope

Viewed 58

Suppose I have the following linked list:

struct ListNode {
   int value;
   struct ListNode *next;
}

And I want to free the memory of my linked list list using the function delete_list:

void delete_list(struct ListNode *list) {
    while (list != NULL) {
        struct ListNode *temp = list;
        list = temp->next;
        free(temp);
    }
}

int main() {
    struct ListNode *list = create_digit_list(56458);
    list_print(list);
//    while (list != NULL) {
//        struct ListNode *temp = list;
//        list = temp->next;
//        free(temp);
//    }
    delete_list(list);
    list_print(list);
    return 0;
}

When I free my list in the same scope I get that list is NULL. But for some reason when using the free my linked list using the my function delete_list and passing my list as a parameter, list isn't NULL and as a result the code prints an infinite loop of garbage. What's the difference between the two ways? what's the correct way to extract the free operation to function?

1 Answers

Actually there are two variables named list. One inside main function and another is the argument of the delete_list function. For simplicity let them be list1 and list2.

When list1 variable is freed inside the main function. The final value of the list1 variable is NULL.

When you pass list1 variable to the function delete_list its value gets copied to the list2 variable present in the scope of delete_list function. When the function returns; the final value of list2 variable is NULL. But list1 still has original address of the struct which you already freed. This leads to garbage values being displayed.

Try renaming your variables and it would me much clearer. If you want you can pass your pointer as a reference which would also affect the original pointer and set it to NULL.

Related