![](/img/trans.png)
[英]Linux Kernel Programming: "Unable to handle kernel NULL pointer dereference"
[英]BUG: kernel NULL pointer dereference when using linux linked list
我试图在操作系统概念第 9 章第 2 章中写作业,它正在编写一个简单的 linux 模块。 我按照书中的示例编写代码,但在删除链表中的项目时出现 null 指针取消引用错误。 这是我的代码。
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");```
birthday_list
全局变量birthday_list
具有隐式初始化{NULL, NULL}
,它不是一个有效的空列表。 这就是simple_exit()
中 null 指针取消引用的原因。 一个有效的空列表有头节点的next
和prev
成员指向头节点本身。
您可以使用LIST_HEAD
宏定义和初始化全局birthday_list
列表变量:
LIST_HEAD(birthday_list);
但是,最好将其声明为static
:
static LIST_HEAD(birthday_list);
LIST_HEAD(birthday_list);
从simple_init()
在simple_init()
, LIST_HEAD(birthday_list);
正在创建一个局部变量birthday_list
,但您应该使用同名的全局变量。 所以只需删除LIST_HEAD(birthday_list);
来自simple_init()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.