我有一个 union 定义如下:
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;
}
我不能通过指针访问 union 成员之一吗?
添加: 现在,答案很明确了。因为我试图在为它分配内存之前访问一个指针,而这种操作是未定义的。 我这样修改了我的代码,然后一切正常。
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 虚拟机。
更新时间:2015-12-16
coredumped 表示段错误。我最近看了一些关于操作系统的书,segmentation fault 意味着你试图访问一些没有为你分配的内存。当我声明一个指针但不为其分配内存时,指针是悬空的。悬垂意味着这个指针有可能指向任何地方,所以根据指向成功与否是合理的。到目前为止一切顺利!
最佳答案
你必须在赋值前为sl
分配内存。否则,sl->next = NULL;
将调用未定义的行为。
关于无法将 union 成员指定为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33829961/