简体   繁体   中英

C - how to free a linked list that has a linked list in its nodes?

As part of a program that I'm writing in kernel space, I have created a linked list that has another linked list in its nodes. The nodes can be two types, either channel which only has an int value and a char* value, or a device file which has an int value and a linked list of channels. but I'm getting NULL pointer reference in my freeList function.

The error that I get is: unable to handle kernel NULL pointer dereference

Any idea how to fix this?

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;
    }
}

If you declare the tmp var outside the loop-while? struct node *curr, *tmp; for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM