Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux/list.h - How to safely remove items from the list?

In the comments of linux/list.h it is written that:

  1. On using list_del_entry: Note: list_empty on entry does not return true after this, the entry is in an undefined state.
  2. For list_del: This is only for internal list manipulation where we know the prev/next entries already!

So, how would I safely remove an object from linked list and make sure that list_empty is functional or make sure that next linked list node deletion is correct?

This is my implementation currently:

struct kool_list{
    int to;
    struct list_head list;
    int from;
};

struct kool_list *tmp;
struct list_head *pos, *q;
struct kool_list mylist;

list_for_each_safe(pos, q, &mylist.list){
         tmp= list_entry(pos, struct kool_list, list);
         printf("freeing item to= %d from= %d\n", tmp->to, tmp->from);
         list_del(pos);
         free(tmp);
}
like image 481
newprint Avatar asked Mar 11 '13 06:03

newprint


1 Answers

I think you misunderstand the comments. The first one says that list_empty(&entry->list) will not return true. However, if you remove all elements from the list (the way you do it is correct) and do list_empty(&mylist.list) you will get true as a result.

If for some reason you want to keep the entry's struct list_head in an internally consistent state, use list_del_init.

Secondly, __list_del is for internal usage only, list_del is fair game.

like image 61
Michael Foukarakis Avatar answered Oct 08 '22 21:10

Michael Foukarakis