c - LIST_HEAD_INIT 和 INIT_LIST_HEAD 之间的区别

标签 c linux-kernel linked-list

我正在尝试了解 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;
}

最佳答案

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()。内核源码中有很多例子。

关于c - LIST_HEAD_INIT 和 INIT_LIST_HEAD 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10262017/

相关文章:

c - srand/rand 缓慢变化的起始值

c - 更多地了解 fseek() 和 EOF IN C

C do while 循环用户选择

php - 用 C 语言编写的基本 Web 服务器,支持 PHP

linux - 如何使用 strstrip 分两部分解析字符串

c - 从单链表中删除节点——使用 MALLOC/FREE

linux - 为什么在linux内核中使用单哈希桶哈希表

linux - 为什么 cgroup 的内存子系统在进程允许内存超过 cgroup 限制时使用 oom-killer 而不是返回内存分配失败?

c - 将链表保存并加载到二进制文件 (C)

c - C 中带头节点的链表