C - 如何释放在其节点中具有链表的链表?

标签 c memory linked-list free

作为我在内核空间中编写的程序的一部分,我创建了一个链表,该链表的节点中有另一个链表。 节点可以是两种类型,一种是仅具有 int 值和 char* 值的 channel ,要么是具有 int 值和 channel 链表的设备文件。但是我在我的 freeList 函数中得到了 NULL 指针引用。

我得到的错误是:无法处理内核 NULL 指针取消引用

知道如何解决这个问题吗?

struct node {
    int val;
    char* msg;
    struct node* headOfIdList;
    struct node* next;
};

static void addChannel(struct node* head, int id, char* msg) {
    printk(KERN_INFO "creating channel\n");
    struct node *curr ;
    curr=head;
    while (curr->next != NULL) {
        curr = curr->next;
    }
    curr->next = kmalloc(sizeof(struct node), GFP_KERNEL);
    curr->next->val = id;
    curr->next->msg = msg;
    curr->next->headOfIdList = NULL;
    curr->next->next = NULL;
    printk(KERN_INFO "channel created\n");
}

static void addFile(struct node* head, int minor) {
    printk(KERN_INFO "creating file\n");
    struct node *curr ;
    curr=head;
    while (curr->next != NULL) {
        curr = curr->next;
    }
    curr->next = kmalloc(sizeof(struct node), GFP_KERNEL);
    curr->next->val = minor;
    curr->next->msg = NULL;
    curr->next->headOfIdList = NULL;
    curr->next->next = NULL;
    printk(KERN_INFO "file created\n");
}

static struct node* find(struct node* head, int val) {
    printk(KERN_INFO "looking for node\n");
    struct node *curr ;
    curr=head;
    while (curr != NULL) {
        if (curr->val == val) {
            return curr;
        }
        curr = curr->next;
    }
    return NULL;
}

static void freeList(struct node* head) {
    printk(KERN_INFO "freeing list\n");
    struct node *curr ;
    curr=head;
    while (curr != NULL) {
        struct node *tmp = curr->next;
        if (curr->headOfIdList != NULL) {
            freeList(curr->headOfIdList);
        }
        kfree(curr);
        curr = tmp;
        //curr=curr->next;
    }
}

最佳答案

如果在 loop-while 之外声明 tmp 变量? struct node *curr, *tmp; 例如。

关于C - 如何释放在其节点中具有链表的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47910169/

相关文章:

c - C 中指向动态数组的指针

c - IEEE 754 : is v *= -1 always guaranteed to be the same as v = -v?

c++ - 为什么 malloc(0) 在 "Inside the C++ Object Model?"有用

c++ - 链表 - 当我使用 -> 打印函数时程序中断

c - 内存泄漏与否 - 链表

C程序排序链表

交叉编译libjson-c : Make unsuccessful in libjson-c, Linkhash.c警告

c - 机器级内存理论

c - JACK 语言的 Lexer 中的段错误

powershell - 获取Powershell变量的内存地址