Skip to content
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

Clarification about reinterpreting memory through over-sized type #39

Open
topolarity opened this issue Mar 23, 2022 · 0 comments
Open

Comments

@topolarity
Copy link

The equivalent of this test in C is UB according to ubsan:

const bytes align(4) = [_]u8{ 1, 2, 3, 4 };
const S = extern struct {
    a: u16,
    b: u16,
    c: u32,
};

const x = @ptrCast(*const S, &bytes);
var p = &x.b; // TODO: Triggers ubsan for CBE, since @sizeOf(S) > @sizeOf(bytes)

const expected = switch (native_endian) {
    .Little => 0x0403,
    .Big => 0x0304,
};
try expect(p.* == expected);

The problem is that we're reinterpreting memory using a type larger than the underlying object. The load itself does not exceed the region of the underlying object however, so this behavior could conceivably be well-defined in Zig.

Is this UB in Zig?

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

1 participant