Skip to content

std.mem.zeroes does not zero entire extern union #17258

@Jarred-Sumner

Description

@Jarred-Sumner

Zig Version

0.12.0-dev.163+6780a6bbf

Steps to Reproduce and Observed Behavior

  1. Run zig test repro.zig
const Union = extern union {
    foo: u32,
    bar: f64,
};

const std = @import("std");
test {
    var a = std.mem.zeroes(Union);
    try std.testing.expectEqual(@as(f64, @bitCast(a)), 0.0);
}
  1. Test fails:
Test [1/1] test_0... expected 2.121995791e-314, found 0.0e+00
Test [1/1] test_0... FAIL (TestExpectedEqual)
/Users/jarred/zig/0.12.0-dev.163+6780a6bbf/files/lib/std/testing.zig:84:17: 0x10483c7fb in expectEqual__anon_1277 (test)
                return error.TestExpectedEqual;
                ^
/Users/jarred/Desktop/repro.zig:9:5: 0x10483c9a3 in test_0 (test)
    try std.testing.expectEqual(@as(f64, @bitCast(a)), 0.0);
    ^
0 passed; 0 skipped; 1 failed.
error: the following test command failed with exit code 1:
/Users/jarred/Code/bun/zig-cache/o/abfa20c47b954fb9fb1e2825bfe8f879/tes

Expected Behavior

The name zeroes implies it is zero-ing the bytes, but it is not zero-ing the bytes.

For an extern union, it is assigning a default value for the first field and ignoring the rest of the bytes. That causes the test above to fail.

However, it also leaves alignment bytes undefined, causing this test snippet to fail:

const Padded = struct {
    foo: u32,
    bar: f64 align(128),
};

const std = @import("std");
test {
    var a = std.mem.zeroes(Padded);
    var bytes = std.mem.asBytes(&a);
    for (bytes) |b| {
        std.debug.assert(b == 0);
    }
}

Partially relevant issues:

I suggest either renaming std.mem.zeroes to std.mem.init to more clearly say what it is doing, or to make it actually do @memset(bytes, 0)

It would be very helpful for serialization code if there was a way to always zero-initialize a struct/union by default (including when using Struct{} ) or to specify a container should always be zero-initialized

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorstandard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions