Segfault with silly union

I was just playing around with unions and accidentally writing this silly type:

const std = @import("std");

const Tree = union { leaf: []const u8, node: Tree };

pub fn main() void {
    var t = Tree{ .leaf = "hi" };
    std.debug.print("{}", .{t});
}

which does compile, but segfaults on MacOS with version 0.12.0-dev.185+49075d205.

Not sure if this (recursive?) type should not be allowed in the first place?

It’s segfaulting because the compiler cannot predict the size of the node field. So to fix it you just need to specify that it’s a pointer, like this:

const std = @import("std");

const Tree = union { leaf: []const u8, node: *Tree };

pub fn main() void {
    var t = Tree{ .leaf = "hi" };
    std.debug.print("{s}", .{t.leaf});
}

Great, thanks for the quick reply! Yes I was actually not expecting a Zig program to segfault, but this is more because of the languages I come from and is of course a totally wrong assumption :sweat_smile:. Thanks again.

It’s not actually your Zig program that segfaults, it’s the compiler that segfaults.
That’s definitely a bug in the compiler.

1 Like

This is

Proper behavior would be a compile error that says something like “exceeded 1000 branches”.

1 Like

Cool, thanks all for the replies.