Skip to content

packed struct hidden padding issue #14887

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
b0bleet opened this issue Mar 11, 2023 · 3 comments
Closed

packed struct hidden padding issue #14887

b0bleet opened this issue Mar 11, 2023 · 3 comments
Labels
bug Observed behavior contradicts documented or intended behavior

Comments

@b0bleet
Copy link

b0bleet commented Mar 11, 2023

Zig Version

0.11.0-dev.1812+26196be34

Steps to Reproduce and Observed Behavior

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

pub fn main() anyerror!void {
    const e820map = packed struct {
        addr: u64,
        size: u64,
        type: u32,
    };
    try expect(@sizeOf(e820map) == 20);
}

Output:

$ zig run check.zig
error: TestUnexpectedResult
/opt/zig/lib/std/testing.zig:509:14: 0x20d807 in expect (test)
    if (!ok) return error.TestUnexpectedResult;
             ^
/tmp/check.zig:30:5: 0x20b695 in main (test)
    try expect(@sizeOf(e820map) == 20);
    ^

Expected Behavior

packed struct size should be 20 bytes.

@b0bleet b0bleet added the bug Observed behavior contradicts documented or intended behavior label Mar 11, 2023
@nektro
Copy link
Contributor

nektro commented Mar 11, 2023

is it 24 ? packed structs create an integer that is in bits the sum of all the fields and primarily used for bit-packing non-power-of-two values into one. here your struct is lowered as a u160 and likely padded to become either a u192 or u256 during codegen. also note you can still assert 20 with @bitSizeOf(e820map)/8.

if what you are trying to do is guarantee layout of fields of "normal" size you are likely looking for extern struct instead.

https://github.com/ziglang/zig/blob/26196be34/src/type.zig#L3577

@b0bleet
Copy link
Author

b0bleet commented Mar 12, 2023

I expected 20 bytes so padding bytes should be ignored, I tried it with 0.9.0 version it works as expected:
https://godbolt.org/z/rrb4WGxeK

@Vexu
Copy link
Member

Vexu commented Mar 12, 2023

Packed structs were changed in 0.10.0, see #5049

@Vexu Vexu closed this as completed Mar 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Observed behavior contradicts documented or intended behavior
Projects
None yet
Development

No branches or pull requests

3 participants