#Unexpected size for packed struct

1 messages · Page 1 of 1 (latest)

crisp crown
#

When I try to get the @sizeOf a packed struct with 2+4 bytes field, I'd expect to get 6 bytes, but get 8 bytes instead. Is my understanding of "packed" incorrect, or is there some bug here?

Tested on 0.10.0 and 0.11.0-dev.661+d88eb75a6 with identical behavior.

Minimal testcase:


test "packed" {
    try std.testing.expectEqual(@as(usize, 2), @sizeOf(packed struct {a: u16})); // passes
    try std.testing.expectEqual(@as(usize, 6), @sizeOf(packed struct {a: u16, b: u32})); // fails
}

Output:

Test [1/1] test.packed... expected 6, found 8
Test [1/1] test.packed... FAIL (TestExpectedEqual)
heavy crag
#

Packed structs create integer-backed structs. You want an extern struct with align(1) fields, instead:
extern struct {a: u16 align(1), b: u32 align(1)}

#

creating that as a packed struct makes it a u48 or something like that, I think, which will align to 8 bytes.