简体   繁体   中英

C struct->struct->struct->element (usual) segmentation fault

Here is a weird thing:

I've got a struct, which contains pointer to a struct of the same type and pointer to the other type struct, as well as some other value.

struct animal {
    struct animal * father;
    struct race * rc;
    int age;
};

struct race {
    char colour;
};

Everything seems to be ok, when I access value age through father:

animal->father->age

But when I try to access colour of the father's race:

animal->father->rc->colour

I get "segmentation fault". But it would be too easy if it would hapen every time. It sometimes does, sometimes doesn't work and I don't know what is the factor that makes it unstable. The other thing that always work is:

animal->rc->colour

Is it possible that you can join up to two pointers and then the problem might occur? I use up-to-date gcc.

If it works fine at times and doesn't at other times, the problem is almost certainly with memory allocation. If you could post how you've assigned the values right up from the declaration, you should be able to get help here soon.

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