Skip to content

Union fields overwritten in an unexpected way #22938

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
HulluKana opened this issue Feb 18, 2025 · 2 comments
Closed

Union fields overwritten in an unexpected way #22938

HulluKana opened this issue Feb 18, 2025 · 2 comments
Labels
bug Observed behavior contradicts documented or intended behavior

Comments

@HulluKana
Copy link

Zig Version

0.13.0

Steps to Reproduce and Observed Behavior

main.zig:

const std = @import("std");

const Struct = struct { a: u32, b: u32 };
const Union = union { x: u32, y: Struct };

pub fn main() !void {
    var example = Union{ .x = 1 };
    example = .{ .y = .{ .a = 2, .b = example.x } };
    std.debug.print("{d}\n", .{example.y.b});
}

run zig build run and get 2 as output

Below is a link to the compiler explorer page containing the same code in both zig and c++ alongside the outputted assembly and printed result.
https://godbolt.org/z/bTYGqWqE9
You can see that c++ outputs 1 whereas zig outputs 2. Taking a look at the assembly, gcc achieves this result by saving the previous value of the example union to eax before overwriting the memory in that address. Zig, however, overwrites the address of the previous value before saving it anywhere, giving the unexpected result of 2.

Expected Behavior

The expected behavior is exactly what gcc does in the linked compiler explorer page. However, if zig overwriting the previous result without saving it is intentional, I would have expected there to be a compiler error. Instead, zig failed silently.

@HulluKana HulluKana added the bug Observed behavior contradicts documented or intended behavior label Feb 18, 2025
@cryptocode
Copy link
Contributor

See #12251 and linked issues

@HulluKana
Copy link
Author

I see. I didn't notice that when looking for duplicates. Well, I guess I can close this issue then.

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

2 participants