list_for_each引起的问题

    在linux里内核通用列表中list_for_each经常被使用。但这里有一点值得注意,最近在自己项目里就碰到了。

list_for_each的定义如下:

#define list_for_each(pos, head) \

    for(pos = (head)->next; pos != (head); pos = pos->next)

list_del的定义如下:

void list_del(struct list_head *entry)

{

    __list_del(entry->entry->prev, entry->next);

    entry->next = LIST_POSITION1;

    entry->prev = LIST_POSITION2;

}

    从定义中可以看到如果在list_for_each遍历过程中使用list_del,会出问题。list_del后,pos的next,prev都已经变为NULL, pos = pos->next运行时就会异常访问。

    当在遍历列表时,应该使用list_for_each_safe;定义如下

#define list_for_each_safe(pos, n, head) \

    for(pos = (head)->next, n = pos->next; pos != (head);

        pos = n, n = pos->next)

原文地址:https://www.cnblogs.com/Mingxx/p/2095025.html