Skip to content
This repository was archived by the owner on Nov 23, 2025. It is now read-only.
This repository was archived by the owner on Nov 23, 2025. It is now read-only.

Clarification about reinterpreting memory through over-sized type #39

@topolarity

Description

@topolarity

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions