I am going through the CS50 course, and this last part of code was written by the instructor to free the memory used :
ptr = list;
while (ptr != NULL)
{
node *next = ptr->next;
free(ptr);
ptr = next;
}
I understand the need to use next as a temporary pointer, but why is "ptr" (a temporary point for the original pointer to the start of the linked list "list" used to free the memory? Is there any reason for not using "list" directly?
while (list != NULL)
{
node *next = list->next;
free(list);
list = next;
}
I tried doing this instead, and it seems to work the same; are there any concerns about freeing list directly?
At around 1:22:00 (one hour and twenty-two minutes) in CS50x 2023 - Lecture 5 - Data Structures, this code is shown.
The temporary ptr
exists simply because the lecturer uses it to first print the contents of the list, without losing track of the root node (list
itself).
node *ptr = list;
while (ptr != NULL)
{
printf("%i\n", ptr->number);
ptr = ptr->next;
}
After this loop, ptr
is NULL
.
ptr
is then reused (again set to list
beforehand) for the loop that frees all the nodes, as seen in your first snippet.
This is purely a style choice - you could just as well use just list
if you do not care to retain the value it holds (useless after free
). In fact, in a previous year's lecture (~ 1:07:00 in CS50 2021 in HDR - Lecture 5 - Data Structures), the code
while (list != NULL)
{
node *tmp = list->next;
free(list);
list = tmp;
}
is used, which does just that.