From: rpjday@crashcourse.ca (Robert P. J. Day) Date: Thu, 7 May 2015 07:05:29 -0400 (EDT) Subject: About head of kernel linked list structure In-Reply-To: <1D347A71-9393-49DD-9EDE-464D5AB265EA@gmail.com> References: <266D09DB-B80D-4DAC-85D9-DFB444A1015D@gmail.com> <1D347A71-9393-49DD-9EDE-464D5AB265EA@gmail.com> Message-ID: To: kernelnewbies@lists.kernelnewbies.org List-Id: kernelnewbies.lists.kernelnewbies.org 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 ========================================================================