I\'m learning how to use the kernel linked-list API from list.h.
I learned that I need to use list_for_each_safe()
when deleting nodes off with list_d
That is necessary because list_del
internally modifies the value of pos
fields. In your example the loop body even frees the memory occupied by pos
. Suppose that you would use unsafe version of the loop:
for (pos = (head)->next; pos != (head); pos = pos->next)
After executing the loop body pos
pointer becomes invalid breaking the increment expression: pos = pos->next
.
As opposite, the safe foreach pre-saves the value of pos->next
in a temporary variable and then refers to the latter instead of dereferencing pos
:
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)