Reputation: 21
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.
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!
Upvotes: 0
Views: 330
Reputation: 106012
You have to allocate memory for sl
before assignment. Otherwise, sl->next = NULL;
will invoke undefined behavior.
Upvotes: 3
Reputation: 234685
A union
is a tricky beast in C. Undefined behaviour is never too far away. In detail:
simple_list *sl; sl->next = NULL;
The behaviour is undefined. You haven't assigned the pointer sl
to any memory.
simple_list sl1; sl1.next = NULL;
That's fine. Just don't attempt to read back the s
member, as the behaviour on doing so is undefined.
simple_list *sl2; sl->next = sl2;
No, this is undefined behaviour too, as you're reading an uninitialised pointer value.
The third point is quite subtle. Most folk know that dereferencing an uninitialised pointer is undefined, but reading one too is also undefined in most instances; this one included.
Upvotes: 3
Reputation: 19864
Allocate memory to your pointer s1
.
s1 = malloc(sizeof(union simple_list));
Also this code will not compile.
You need to have your union type for a variable inside the union.
union simple_list
{
union simple_list *next;
int *s;
}
Upvotes: 1
Reputation: 10947
You need to allocate the object!
simple_list* s1 = malloc(sizeof(simple_list));
s1->next = NULL;
Upvotes: 1
Reputation: 60065
simple_list *sl;
Declares pointer to simple_list
, doesn't allocate memory and pointer doesn't point to valid union
.
sl->next = NULL; // core dumped, why?
because see above. This union instance doesn't exist.
Upvotes: 2