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

时间:2017-12-20 16:08:31

标签: c memory linked-list free

作为我在内核空间编写的程序的一部分,我创建了一个链接列表,其节点中有另一个链表。 节点可以是两种类型,可以是仅具有int值和char *值的通道,也可以是具有int值和通道链接列表的设备文件。但我在我的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;
    }
}

1 个答案:

答案 0 :(得分:0)

如果你在循环外声明tmp var而while?例如struct node *curr, *tmp;