Skip to content

Function parameter is not immutable #9713

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
jean-dao opened this issue Sep 9, 2021 · 1 comment
Closed

Function parameter is not immutable #9713

jean-dao opened this issue Sep 9, 2021 · 1 comment
Milestone

Comments

@jean-dao
Copy link
Contributor

jean-dao commented Sep 9, 2021

Came across this behavior, looks like a bug to me:

const std = @import("std");

const Nested = struct {
    x: u32,
};

const Test = struct {
    nested: Nested,

    fn update(self: *Test, arg: Nested) void {
        std.debug.print("t={} arg={}\n", .{self, arg});
        self.nested = .{ .x = 0 };
        std.debug.print("t={} arg={}\n", .{self, arg});
        self.nested = arg;
        std.debug.print("t={} arg={}\n", .{self, arg});
    }
};

pub
fn main() void {
    var t = Test{ .nested = .{ .x = 42 }};
    t.update(t.nested);
}

will print:

t=Test{ .nested = Nested{ .x = 42 } } arg=Nested{ .x = 42 }
t=Test{ .nested = Nested{ .x = 0 } } arg=Nested{ .x = 0 }
t=Test{ .nested = Nested{ .x = 0 } } arg=Nested{ .x = 0 }

When passing both a pointer to a struct and a member of this struct, the member is passed by reference (it seems), so changing the struct will change the second argument.

Tested with zig-linux-x86_64-0.9.0-dev.946+6237dc0a.

@Vexu
Copy link
Member

Vexu commented Sep 9, 2021

This has the same root cause as #3696 and #4021 which is that the compiler doesn't recognize that there will be aliasing issues and passes the argument via a hidden pointer. The workaround is to copy the parameter to stack first but the underlying issue has not yet been solved.

@Vexu Vexu closed this as completed Sep 9, 2021
@andrewrk andrewrk added this to the 0.9.0 milestone Nov 20, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants