Skip to content

Segfault when embedding cImport struct in a zig struct #8122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mil opened this issue Mar 2, 2021 · 1 comment
Closed

Segfault when embedding cImport struct in a zig struct #8122

mil opened this issue Mar 2, 2021 · 1 comment
Milestone

Comments

@mil
Copy link
Contributor

mil commented Mar 2, 2021

Running into a strange segfault when using @cImport:

Create sample.h in a folder:

typedef struct somecstruct {
    usize foo;
} somecstruct;

And then create foo.zig as:

const std = @import("std");
const sample = @cImport({
    @cInclude("sample.h");
});

pub const Foo = struct { 
  Bar: sample.somecstruct
};

pub fn main() !void {
    var d = @intCast(usize, 37);
    std.debug.warn("Converted {}\n", .{d});
    var x = .{ .Bar = .{ .foo = d } };
}

Run with:

zig run -lc foo.zig -I./

Produces:

> zig run -lc foo.zig -I./
Converted 37
Segmentation fault at address 0x201d90
/home/m/foo.zig:13:33: 0x203ce2 in main (foo)
    var x = .{ .Bar = .{ .foo = d } };
                                ^
/usr/lib/zig/std/start.zig:345:37: 0x204031 in std.start.main (foo)
            const result = root.main() catch |err| {
                                    ^
zsh: abort      zig run -lc foo.zig -I./

Tested on musl / Alpine linux with zig version:

> zig version
0.8.0-dev.1343+3c0238e73
@Vexu
Copy link
Member

Vexu commented Mar 2, 2021

Duplicate of #3915.

Adding a type to x makes this work just fine:

pub const Foo = struct { 
  Bar: sample.somecstruct
};

pub fn main() !void {
    var d = @intCast(usize, 37);
    std.debug.warn("Converted {}\n", .{d});
    var x: Foo = .{ .Bar = .{ .foo = d } };
}

@Vexu Vexu closed this as completed Mar 2, 2021
@andrewrk andrewrk added this to the 0.8.0 milestone Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants