LIST_HEAD_INIT和INIT_LIST_HEAD之间的区别

问题描述 投票:8回答:2

我正在尝试了解Linux内核链表API。

根据Linux Kernel Linked List,我应该通过INIT_LIST_HEAD初始化列表头,但here (Linux Kernel Program)建议使用LIST_HEAD_INIT代替。

这是我写的一个工作代码,但我不确定我是否以正确的方式做到了。有人可以验证它没问题吗?

#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;
}
c linux-kernel linked-list
2个回答
12
投票

快速LXR搜索显示:

#define LIST_HEAD_INIT(name) { &(name), &(name) }

static inline void INIT_LIST_HEAD(struct list_head *list)
{
        list->next = list;
        list->prev = list;
}

所以INIT_LIST_HEAD得到一个struct list_head *并初始化它,而LIST_HEAD_INIT以适当的方式返回传递指针的地址,用作列表的初始化器:

struct list_head lst1;
/* .... */
INIT_LIST_HEAD(&lst1);



struct list_head lst2 = LIST_HEAD_INIT(lst2);

22
投票

LIST_HEAD_INIT是一个静态初始化器,INIT_LIST_HEAD是一个函数。他们都将list_head初始化为空。

如果你静态声明list_head,你应该使用LIST_HEAD_INIT,例如:

static struct list_head mylist = LIST_HEAD_INIT(mylist);

您应该使用INIT_LIST_HEAD()作为动态分配的列表头,通常是另一个结构的一部分。内核源代码中有很多例子。

© www.soinside.com 2019 - 2024. All rights reserved.