【问题标题】:C - how to free a linked list that has a linked list in its nodes?C - 如何释放在其节点中有链表的链表?
【发布时间】:2018-06-03 06:11:10
【问题描述】:

作为我在内核空间中编写的程序的一部分,我创建了一个链表,它的节点中有另一个链表。 节点可以是两种类型,一种是只有 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;
    }
}

【问题讨论】:

  • while (curr->next != NULL) { curr = curr->next; } - 你是说while (curr != NULL) 吗?
  • @EugeneSh。这是在添加函数中,我这样做是为了在curr 中获取列表中的最后一个元素,然后将新元素添加到curr->next。问题出在freeList 函数中。
  • 您将tmp 设置为curr->next,但随后您再次将其移动到curr = tmp; curr=curr->next;。你不需要最后一行。它正在跳过一个元素。
  • @EugeneSh。我删除了最后一行,但仍然出现同样的错误。

标签: c memory linked-list free


【解决方案1】:

如果你在 loop-while 之外声明 tmp var?以struct node *curr, *tmp; 为例。

【讨论】:

    猜你喜欢
    • 2011-09-19
    • 1970-01-01
    • 2013-07-23
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    相关资源
    最近更新 更多