title: Why do we need list_for_each_safe() in for deleting nodes in kernel linked list?
body: <p>I'm learning how to use the kernel linked-list API from <a href="http://lxr.free-electrons.com/source/include/linux/list.h">list.h</a>.</p>
  
  <p>I learned that I need to use <code>list_for_each_safe()</code> when deleting nodes off with <code>list_del()</code> instead of using <code>list_for_each()</code>.</p>
  
  <p>Code for <code>list_for_each_safe()</code>:</p>
  
  <pre><code>#define list_for_each_safe(pos, n, head) \
      for (pos = (head)-&gt;next, n = pos-&gt;next; pos != (head); \
          pos = n, n = pos-&gt;next)
  </code></pre>
  
  <p>Code for <code>list_for_each()</code>:</p>
  
  <pre><code>    for (pos = (head)-&gt;next; pos != (head); pos = pos-&gt;next)
  </code></pre>
  
  <p>I notice they both are very similar except that the <code>_safe</code> version takes an extra argument to be used as 'temporary storage' (stated here, <a href="http://lxr.free-electrons.com/source/include/linux/list.h">list.h</a>).</p>
  
  <p>I understand when to apply the function correcly, <code>_safe</code> version for deleting, normal version for accessing, but I'm curious how the extra argument made it 'safe'? </p>
  
  <p>Consider the following, where I'm deleting every node in a linked list using <code>list_for_each_safe()</code>:</p>
  
  <pre><code>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, &amp;mylist.list){
           tmp= list_entry(pos, struct kool_list, list);
           printf("freeing item to= %d from= %d\n", tmp-&gt;to, tmp-&gt;from);
           list_del(pos);
           free(tmp);
      }
  </code></pre>
  
  <p>How does giving <code>q</code> help in deleting?</p>
  
  <p>Thanks for any help!</p>