Why do we need list_for_each_safe() in for deleting nodes in kernel linked list?

后端 未结 2 1920
臣服心动
臣服心动 2021-02-13 03:43

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

相关标签:
2条回答
  • 2021-02-13 04:11
    pos = start;
    del(pos);
    pos = pos->next;
    

    as opposed to

    pos = start;
    n = pos->next;
    del(pos);
    pos = n;
    

    if del() is free() and memset(), pos->next is undefined

    0 讨论(0)
  • 2021-02-13 04:13

    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)
    
    0 讨论(0)
提交回复
热议问题