Skip to content

Incorrect behaviour when writing to a field of a packed union that is not a multiple of 8 bits #17360

@kcbanner

Description

@kcbanner

Zig Version

0.12.0-dev.700+376242e58

Steps to Reproduce and Observed Behavior

const std = @import("std");
const testing = std.testing;

const U = packed union {
    foo: u12,
    bar: u29,
    baz: u64,
};

test {
    var u: U = undefined;
    u.baz = 0xbbbbbbbb_bbbbbbbb;
    u.foo = 0xeee;

    try testing.expectEqual(@as(u12, 0xeee), u.foo);
    try testing.expectEqual(@as(u29, 0x1bbbbeee), u.bar);
    try testing.expectEqual(@as(u64, 0xbbbbbbbb_bbbbbeee), u.baz);
}
$ zig test packed_union.zig
Test [1/1] test_0... expected 465288942, found 465243886
Test [1/1] test_0... FAIL (TestExpectedEqual)
/home/kcbanner/kit/zig-linux-x86_64-0.12.0-dev.700+376242e58/lib/std/testing.zig:84:17: 0x22462b in expectEqual__anon_1104 (test)
                return error.TestExpectedEqual;
                ^
/mnt/c/cygwin64/home/kcbanner/temp/packed_union.zig:16:5: 0x22478a in test_0 (test)
    try testing.expectEqual(@as(u29, 0x1bbbbeee), u.bar);

Expected is 0x1bbbbeee, but the actual value is 0x1bbb0eee. The failure also occurs in the x86_64 backend (-fno-llvm -fno-lld).

I confirmed with a debugger this is on the write side of things, after foo is written, the backing memory contains 0xbbbbbbbbbbbb0eee.

Expected Behavior

Test passes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorfrontendTokenization, parsing, AstGen, Sema, and Liveness.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions