Difference between LIST_HEAD_INIT and INIT_LIST_HEAD

I am trying to understand the Linux kernel linked list API.

According to the Linked Linux Kernel List I have to initialize the INIT_LIST_HEAD list INIT_LIST_HEAD , but here (Linux Kernel Program) it is suggested to use LIST_HEAD_INIT .

Here is the working code I wrote, but I'm not sure if I did it right. Can anyone verify that this is normal?

 #include <stdio.h> #include <stdlib.h> #include "list.h" typedef struct edge_attr { int d; struct list_head list; } edge_attributes_t; typedef struct edge { int id; edge_attributes_t *attributes; } edge_t; int main () { int i; struct list_head *pos; edge_attributes_t *elem; edge_t *a = (edge_t*)malloc(sizeof(edge_t)); a->id = 12; a->attributes = (edge_attributes_t*) malloc(sizeof(edge_attributes_t)); INIT_LIST_HEAD(&a->attributes->list); for (i=0; i<5; ++i) { elem = (edge_attributes_t*)malloc(sizeof(edge_attributes_t)); elem->d = i; list_add(&elem->list, &a->attributes->list); } list_for_each(pos, &(a->attributes->list)) { elem = list_entry(pos, edge_attributes_t, list); printf("%d \n", elem->d); } return 0; } 
+7
source share
2 answers

A quick search for LXR shows:

 #define LIST_HEAD_INIT(name) { &(name), &(name) } static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list; list->prev = list; } 

Thus, INIT_LIST_HEAD receives a struct list_head * and initializes it, while LIST_HEAD_INIT returns the address of the passed pointer in suitable for use as an initializer for the list:

 struct list_head lst1; /* .... */ INIT_LIST_HEAD(&lst1); struct list_head lst2 = LIST_HEAD_INIT(lst2); 
+11
source

LIST_HEAD_INIT is a static initializer, INIT_LIST_HEAD is a function. Both of them initialize a list_head empty.

If you statically declare a list_head , you should use LIST_HEAD_INIT , for example:

 static struct list_head mylist = LIST_HEAD_INIT(mylist); 

You should use INIT_LIST_HEAD() for the list header, which is dynamically allocated, usually part of another structure. There are many examples in the kernel source.

+21
source

Source: https://habr.com/ru/post/913806/


All Articles