6.下面的代码是 linux kernel的代码,请指出其中的错误来: struct student{ int id; char name[20]; struct list_head list; }; static LIST_HEAD(student_list); static DEFINE_MUTEX(student_mutex); static int add_student(struct student *stu) { struct student *new_stu = NULL; if(!stu) { printk(KERN_ ERR " Invalid argument\n"); return -EINVAL; } if (stu->id <= 0){ printk(KERN_ ERR "Invalid id\n"); return -EINVAL; } if(!mutex_trylock(&student_mutex)){ printk(KERN_ INFO "Failed to lock mutex\n"); return-EBUSY; } new_stu = kmalloc(sizeof(struct student), GFP KERNEL); if(!new_stu) { printk(KERN ERR "Failed to allocate memory\n"); return -ENOMEM; *new_stu= *stu; list_add_ tail(&new_stu->list, &student_list); printk(KERN_ INFO "Added student: id=%d, name-%s\n", stu->id, stu->name); mutex_unlock(&student_mutex); return 0; }
时间: 2023-12-03 19:45:37 浏览: 60
下是代码中的错误:
1. `GFP KERNEL` 应该为 `GFP_KERNEL`,多了一个空格。
2. `*new_stu= *stu;` 这行代码应该在 `if(!new_stu) {` 的前面,否则会导致内存泄漏。
修改后的代码如下:
```
struct student{
int id;
char name[20];
struct list_head list;
};
static LIST_HEAD(student_list);
static DEFINE_MUTEX(student_mutex);
static int add_student(struct student *stu) {
struct student *new_stu = NULL;
if(!stu) {
printk(KERN_ERR "Invalid argument\n");
return -EINVAL;
}
if (stu->id <= 0){
printk(KERN_ERR "Invalid id\n");
return -EINVAL;
}
new_stu = kmalloc(sizeof(struct student), GFP_KERNEL);
if(!new_stu) {
printk(KERN_ERR "Failed to allocate memory\n");
return -ENOMEM;
}
*new_stu= *stu;
list_add_tail(&new_stu->list, &student_list);
printk(KERN_INFO "Added student: id=%d, name=%s\n", stu->id, stu->name);
mutex_unlock(&student_mutex);
return 0;
}
```
阅读全文