About head of kernel linked list structure

Robert P. J. Day rpjday at crashcourse.ca
Thu May 7 07:05:29 EDT 2015


On Thu, 7 May 2015, Huaicheng Li wrote:

> Hi Robert,
>
> You got my point and I’m sorry for not stating it in a clear way.
> You are right about the "prev-to-left" and "next-to-right" when
> drawing the line. At that time, I just wanted to show which node
> they were pointing at.  Anyway, you solved my puzzle. Also thanks
> for your excellent article.

  it's a moderately common mistake to not realize that the "head" of a
list is represented by just another "struct list_head" like all the
other elements in the list, but it's a special list_head in the sense
that it does ***not*** represent a valid enclosing data payload, and
should never be dereferenced.

  the way i normally demonstrate this is to show the following macro
from include/linux/list.h:

/**
 * list_for_each        -       iterate over a list
 * @pos:        the &struct list_head to use as a loop cursor.
 * @head:       the head for your list.
 */
#define list_for_each(pos, head) \
        for (pos = (head)->next; pos != (head); pos = pos->next)

  note well how iteration over a list starts from "(head)->next" and
continues until returning back to "(head)" while *not* including that
last address to be dereferenced.

  this also has the (obvious) consequence that you can never forget
which element in a list is the head; otherwise, you'll never know
which element you're not supposed to dereference.

rday

-- 

========================================================================
Robert P. J. Day                                 Ottawa, Ontario, CANADA
                        http://crashcourse.ca

Twitter:                                       http://twitter.com/rpjday
LinkedIn:                               http://ca.linkedin.com/in/rpjday
========================================================================


More information about the Kernelnewbies mailing list