【发布时间】:2015-11-20 15:08:40
【问题描述】:
我有一个联合定义如下:
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 虚拟机。
更新:2015-12-16
核心转储意味着分段错误。我最近读了一些关于操作系统的书,分段错误意味着您尝试访问一些尚未为您分配的内存。当我声明一个指针但不为其分配内存时,指针悬空。悬空意味着这个指针可以指向任何地方,因此成功或不成功地引用该点是合理的。到目前为止一切顺利!
【问题讨论】: