尝试使用copy_to_user函数访问结构数组时出现0 ip(null)错误14

尝试使用copy_to_user函数访问结构数组时出现0 ip(null)错误14,c,arrays,linux,struct,linux-kernel,C,Arrays,Linux,Struct,Linux Kernel,请记住,我用C语言编程已经有一段时间了。我正在尝试将一个结构数组从内核空间移动到用户空间。下面是我在/var/log/kern.log中看到的错误: userspace[5091]: segfault at 0 ip (null) sp 00007fff21250d00 error 14 in userspace[400000+5000]`. 我的代码流是在用户端声明一个结构数组,将该地址传递给内核端。从使用该用户空间地址的内核端,我将一个结构数组复制到该用户空间地址。然后

请记住,我用C语言编程已经有一段时间了。我正在尝试将一个结构数组从内核空间移动到用户空间。下面是我在
/var/log/kern.log
中看到的错误:

userspace[5091]: segfault at 0 ip           (null) sp 00007fff21250d00 error 14 in userspace[400000+5000]`.
我的代码流是在用户端声明一个结构数组,将该地址传递给内核端。从使用该用户空间地址的内核端,我将一个结构数组复制到该用户空间地址。然后回到用户空间,我尝试迭代并打印来自该结构数组的值。这就是我的seg故障

标题.h

#define MAX_CONTS             100

typedef struct cont_struct {
   int id;
   u32 pid;
} __attribute__((packed)) cont_struct;
userspace.c

 include "header.h"

 cont_struct conts[MAX_CONTS];
 //cont_struct *conts = (cont_struct *)malloc(MAX_CONTS * sizeof(cont_struct));
 memset(conts, 0, sizeof(conts));
//by this point I hope the array of structs has been properly copied from kernel space to user space
for (size_t i = 0 ; i < MAX_CONTS; i++)
    {
     fprintf(fout, "id: %u pid: %u\n", conts[i].id, conts[i].pid);
   }
我使用proc文件系统将
conts
的值传递给内核端。我已经证实它是正确通过的。下面是内核代码,我尝试使用
copy\u to\u user
函数将结构数组复制到用户空间
conts
是用户空间地址

内核空间

 include "header.h"

 cont_struct kern_conts[MAX_CONTS];
 kern_conts[0].pid = 111;
 kern_conts[0].id = 1;
 kern_conts[1].pid = 222;
 kern_conts[1].id = 2;

 // conts is the value passed from userspace
 if ( copy_to_user((void *)conts, kern_conts, sizeof(conts)) ){
     printk("error\n);
 }
稍后,我在用户空间中调用下面的代码,遍历结构数组以打印出值。即使我将
for loop
的结束条件设置为低于100,它仍然会出现seg故障。它也是垃圾值,所以我很确定它没有正确复制数据

userspace.c

 include "header.h"

 cont_struct conts[MAX_CONTS];
 //cont_struct *conts = (cont_struct *)malloc(MAX_CONTS * sizeof(cont_struct));
 memset(conts, 0, sizeof(conts));
//by this point I hope the array of structs has been properly copied from kernel space to user space
for (size_t i = 0 ; i < MAX_CONTS; i++)
    {
     fprintf(fout, "id: %u pid: %u\n", conts[i].id, conts[i].pid);
   }
//至此,我希望结构数组已正确地从内核空间复制到用户空间
对于(大小i=0;i

我的第一个问题是,我是否正确地声明了struct的数组?我在这个论坛上看到过,人们在处理结构数组时使用malloc方法。我已经尝试了两种声明方式,但都不起作用。结构数组在内核端填充/操作。稍后在客户端,当我尝试遍历并打印值时,在遍历数组结束时,它抛出上面提到的错误。非常感谢您的帮助

显示
复制到用户()
;否则,根据信息,问题无法解决。它在if语句中。谢谢。这是一个内核api,不是我写的任何东西。您可以在这里阅读内核模块中的
conts
的确切类型是什么?标题中的segfault似乎与正文中的segfault不匹配?另外:如果
conts
是从用户空间传递的一个值,那么它将成为指针,而不是数组。所以
sizeof(conts)
只是指针的大小,而不是数组的大小。你需要使用计数。我不知道这是不是一个错误,但无论如何,这是一个错误。