Linux / list.h - How to safely remove items from a list?

The linux/list.h say that:

  • When using list_del_entry : Note: list_empty after writing does not return true after that, the recording is in undefined state.
  • For list_del : this is only for internal list processing, where we already know previous / next entries.

So, how could I safely remove an object from a linked list and make sure list_empty is functional or make sure that deleting the linked list node 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); } 
+7
source share
1 answer

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

If for some reason you want to keep the struct list_head in an internal consistent state, use list_del_init .

Secondly, __list_del used for internal use only, list_del is fair play.

+5
source

All Articles