【问题标题】:BUG: kernel NULL pointer dereference when using linux linked listBUG:使用 linux 链表时内核 NULL 指针取消引用
【发布时间】:2021-04-01 01:07:29
【问题描述】:

我正在尝试编写操作系统概念第 9 章第 2 章中的作业,即编写一个简单的 linux 模块。我按照书中的示例编写代码,但在删除链表中的项目时出现空指针取消引用错误。 这是我的代码。

  1 #include <linux/module.h>
  2 #include <linux/kernel.h>
  3 #include <linux/list.h>
  4 #include <linux/slab.h>
  5 /* This function is called when the module is loaded. */
  6 
  7 struct birthday{
  8     int day;
  9     int month;
 10     int year;
 11     struct list_head list;
 12 };
 13 
 14 struct list_head birthday_list;
 15 
 16 int simple_init(void)
 17 {
 18        printk(KERN_INFO "Loading Module\n");
 19        LIST_HEAD(birthday_list);
 20        struct birthday *person;
 21        person = kmalloc(sizeof(*person), GFP_KERNEL);
 22        person->day=24;
 23        person->month=1;
 24        person->year=2000;
 25        INIT_LIST_HEAD(&person->list);
 26        list_add_tail(&person->list, &birthday_list); 
 27        struct birthday *ptr;
 28        list_for_each_entry(ptr, &birthday_list, list){
 29            printk(KERN_INFO "Birthday: %d/%d/%d\n", ptr->year, ptr->month, ptr->day);
 30        }
 31        return 0;
 32 }
 33 
 34 /* This function is called when the module is removed. */
 35 void simple_exit(void) {
 36         printk(KERN_INFO "Removing Module\n");
 37         struct birthday *ptr, *next;
 38 
 39         list_for_each_entry_safe(ptr, next, &birthday_list, list){
 40             printk(KERN_INFO "Birthday: %d/%d/%d\n", ptr->year, ptr->month, ptr->day);
 41             list_del(&(ptr->list));
 42             kfree(ptr);
 43         }
 44 
 45         printk(KERN_INFO "Removing Successfully\n");
 46 }
 47 module_init( simple_init );
 48 module_exit( simple_exit );
 49 
 50 MODULE_LICENSE("GPL");
 51 MODULE_DESCRIPTION("Simple Module");
 52 MODULE_AUTHOR("SGG");```

【问题讨论】:

    标签: c linux


    【解决方案1】:

    初始化全局变量birthday_list

    全局变量birthday_list 具有隐式初始化{NULL, NULL},它不是一个有效的空列表。 这就是 simple_exit() 中的空指针取消引用的原因。 一个有效的空列表有头节点的 nextprev 成员指向头节点本身。

    您可以使用LIST_HEAD 宏定义和初始化全局birthday_list 变量:

    LIST_HEAD(birthday_list);
    

    不过,最好声明为static

    static LIST_HEAD(birthday_list);
    

    simple_init() 中删除LIST_HEAD(birthday_list);

    simple_init() 中,LIST_HEAD(birthday_list); 正在创建一个局部变量birthday_list,但您应该使用同名的全局变量。所以只需从simple_init() 中删除LIST_HEAD(birthday_list);

    【讨论】:

      猜你喜欢
      • 2010-09-25
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多