3 ms·
Yep! To do this properly requires something more like: void free_circularly_linked_list(struct node *head) { struct node *tmp = head->next; wh
by haberman 10y ago
Yep! To do this properly requires something more like:
void free_circularly_linked_list(struct node *head) {
struct node *tmp = head->next;
while (1) {
if (tmp == head) {
/* Has to be a separate case since even assigning
* a dangling pointer is UB I believe? */
free(tmp);
break;
} else {
struct node *next = tmp->next;
free(tmp);
tmp = next;
}
}
}
- deleted 10y ago[deleted]
- ericbb 10y agoI'm not sure what you are trying to achieve by using the infinite loop. There's a more direct way. void free_circularly_linked_list(struct node *head) { struct node *a = head->next; while (a != head) { struct node *b = a->next; free(a); a = b; } free(head); } Great example, by the way!