简体   繁体   中英

Pointer returning NULL from extern structure in C

I have defined following global structure in a .h file:

file1.h

struct kobject_saved {
struct kobject* kobject;
}
extern struct kobject_saved *ksaved;

file1.c

#include <file1.h>

struct kobject_saved *ksaved = kmalloc(sizeof(struct kobject_saved), GFP_KERNEL);
ksaved->kobject = some_kobject; // some_kobject is a initialized pointer to kobj

file2.c

#include <file1.h>

struct kobject *ko = ksaved->kobject;

Here, I am getting the value of kobject to be null. Even though the call to file2.c is made after initialization happens at file1.c

Can you please help me to access kobject without losing the data? Possibly point out where I am going wrong?

Many thanks,

Update: This is my exact code for some_object. I am getting correct address for "ko" though..

void save_my_kobject(struct kobject *ko)
{
        ko_saved = kmalloc(sizeof(struct kobject_saved), GFP_KERNEL);

        *ko_saved = (struct kobject_saved) {
        .kobj = ko
        };

}

Some elements of the source code are missing to clearly understand what you want to do, for example :

struct *ko = ksaved->kobject;

can't be right. I guess you meant :

struct kobject* ko = ksaved->kobject;

You are basically setting a global variable, which will be modified by two source files. It is not a recommended practice (difficult to maintain).

Anyway, if that's what you want to do, you have to define the global variable in one file, and reference it from the second one, as you did. The extern statement would be better remained localized within file2.c .

We don't have your exact sequence, so we don't know how your code behaves. Apparently it doesn't crash, so I guess the malloc from file1.c has worked correctly. That means that file1.c has been run as intended. And it also means that the problem could be this statement :

ksaved->kobject = some_kobject; // some_kobject is a initialized pointer to kobj

might be wrong : maybe some_kobject == NULL ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM