Skip to content

Bug: Function mutates argument when it is also the result location #7412

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
ghost opened this issue Dec 12, 2020 · 1 comment
Closed

Bug: Function mutates argument when it is also the result location #7412

ghost opened this issue Dec 12, 2020 · 1 comment
Milestone

Comments

@ghost
Copy link

ghost commented Dec 12, 2020

Noticed by sinitax on Discord.

Consider the following code:

const std = @import("std");
const Pos = struct { x: i64, y: i64 };

pub fn modify(p: Pos) Pos {
    return Pos{ .x = 1, .y = p.x };
}

pub fn main() !void {
    p = modify(p);
    std.debug.print("{} {}\n", .{ p.x, p.y });
}

The expected output is 1 5, but the actual output is 1 1. This is because p is passed by reference, but also set as the result location; so, the first field assignment mutates it in-place. This is not expected or desired behaviour. To avoid this, when the result location would overlap any argument, we should instead allocate a temporary.

@Vexu
Copy link
Member

Vexu commented Dec 12, 2020

Duplicate of #3696

@Vexu Vexu marked this as a duplicate of #3696 Dec 12, 2020
@Vexu Vexu closed this as completed Dec 12, 2020
@andrewrk andrewrk added this to the 0.8.0 milestone Jan 3, 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

2 participants