我有一个联合定义如下:
union simple_list
{
simple_list *next;
int *s;
};
这是我的主要功能:
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;
}
我不能通过指针访问一个联盟成员吗?
加法: 现在,答案很清楚。因为我在为它分配内存之前尝试访问指针,并且这种操作是未定义的。 我修改了这样的代码,然后一切都没问题。
simple_list *sl = (simple_list*)malloc(sizeof(union simple_list));
但是,我发现了另一个问题:
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;
}
这是否意味着未定义的操作可能(不一定)导致核心转储错误?
我使用gcc 4.8.4编译我的C代码。 Ubuntu 14.04虚拟机。
cored dumped意味着分段错误。我最近读了一些关于操作系统的书,分段错误意味着你试图访问一些没有为你分配的内存。当我声明一个指针但没有为它分配内存时,指针悬空。悬空意味着该指针可以指向任何地方,因此成功或不成功是合理的顺从。到目前为止一切都很好!
答案 0 :(得分:3)
在分配之前,您必须为sl
分配内存。否则,sl->next = NULL;
将调用未定义的行为。
答案 1 :(得分:3)
union
在C中是一个棘手的野兽。未定义的行为永远不会太远。详细说明:
simple_list *sl; sl->next = NULL;
行为未定义。您尚未将指针sl
分配给任何内存。
simple_list sl1; sl1.next = NULL;
没关系。只是不要尝试回读s
成员,因为这样做的行为是 undefined 。
simple_list *sl2; sl->next = sl2;
不,这也是未定义的行为,因为您正在读取未初始化的指针值。
第三点非常微妙。大多数人都知道解除引用一个未初始化的指针是未定义的,但读取一个在大多数情况下也是未定义的;这个包括在内。
答案 2 :(得分:2)
simple_list *sl;
声明指向simple_list
的指针,不分配内存,指针不指向有效union
。
sl->next = NULL; // core dumped, why?
因为见上文。这个联合实例不存在。
答案 3 :(得分:1)
将内存分配给指针s1
。
s1 = malloc(sizeof(union simple_list));
此代码也不会编译。
你需要为联盟中的变量建立联合类型。
union simple_list
{
union simple_list *next;
int *s;
}
答案 4 :(得分:1)
你需要分配对象!
simple_list* s1 = malloc(sizeof(simple_list));
s1->next = NULL;