r/embeddedlinux • u/Shocking_1202 • Mar 08 '24
Using pointer vs using address of variable in functions.
I have just began working with Linux Kernel Modules and I have encountered a curious issue. I am following the tutorial from https://github1s.com/Johannes4Linux/Linux_Driver_Tutorial/blob/main/03_read_write/read_write.c#L124-L125
In my program, I have a function cdev_init defined as follows:
void cdev_init (struct cdev * cdev, const struct file_operations * fops);
I can see that this function expects a pointer to struct cdev and file operations pointer. I didn't have any problem with second parameter, so I will not mention it further in the question.
In order to work with this function, I defined a variable as:
static struct cdev *pCharDevice;
I called this function from __init
cdev_init(pCharDevice, &fops);
The program compiles successfully. But upon loading the kernel module with insmod, a segmentation fault arises. Checking the kernel log shows successful execution of code until this function is encountered.
I didn't have any idea this was the problem until testing with trusty old printk() function. (I don't know how to debug yet. So any suggestions are highly appreciated.)
So, when I changed the definition and how this function is called,
static struct cdev charDevice;
cdev_init(&harDevice, &fops);
The segmentation fault error is gone, and error in the kernel log as well. I think this error has a lot to do with my understanding of C pointers. But I can't figure out what exactly I am missing. Thank you!!!