无法将 union 成员指定为 NULL

标签 c pointers unions

我有一个 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/

相关文章:

c - GDB + TUI + GNU Screen - 将 gdb 输出发送到不同的 screen

c - error C2071 非法存储类,在 C 中定义枚举类型

C - 将指针数据保存/加载到文件

c++ - 包含 union 的结构的复制构造函数

c - 当用户输入某句话时让程序结束

c - 如何在 8-10 字节数据中填充 n 个 16 位值的任意数量的值?

c++ - 引用是否被视为 C++ 中的指针

c - 我释放节点的方式是否正确?

c - 对于不同类型的 var,如何重复使用变量而不出现错误 C2371(重新定义)?

c - 这段代码中union的意义是什么,structure的缺点是什么?