Search code examples
cpointersunions

Cannot assign union member as NULL


I have a union definition as follows:

union simple_list
{
    simple_list *next;
    int *s;
};

This is my main function:

int main()
{
    simple_list *sl;
    sl->next = NULL; // core dumped, why?

    simple_list sl1;
    sl1.next = NULL; // this will be fine

    simple_list *sl2;
    sl->next = sl2; // this also will be fine

    return 0;
}

Can't I access one of union members by pointer?

Additions: Now, the answer is clear. Because I tried to access a pointer before allocating memory for it, and this kind of operation is undefined. I modified my codes like this, then everything is okay.

simple_list *sl = (simple_list*)malloc(sizeof(union simple_list));

However, I find another problem:

int main()
{
    simple_list *sl = (simple_list*)malloc(sizeof(union simple_list));
    sl->next = NULL;  // this should be fine and it does

    simple_list *sl1;
    sl1->next = NULL; // amazing! this also be fine, "fine" means no core dumped

    return 0;
}

Does this means that an undefined operation may(not must) cause core dumped error?

I compile my C codes with gcc 4.8.4. Ubuntu 14.04 virtual machine.

Update:2015-12-16

cored dumped means segmentation fault. I read some books about OS recently, segmentation fault means that you try to access some memory that have not been allocated for you. When I declare a pointer but not allocate memory for it, the pointer is dangling. Dangling means that this pointer is possible to point to anywhere, so it is reasonable deference the point successfully or not successfully. So far so good!


Solution

  • You have to allocate memory for sl before assignment. Otherwise, sl->next = NULL; will invoke undefined behavior.