hey @AndrewCodeDev, thanks for the quick reply!
So, I got some of it right - v is discarded at the end of init
, so &v
is a dangling pointer. But there are still things mysterious.
Here is another example:
const std = @import("std");
const Box = struct {
value: *const u64,
fn one(v: u64) Box {
std.debug.print("address of parameter v {}\n", .{&v});
return .{
.value = &v,
};
}
fn two(v: u64) Box {
var tmp = v;
std.debug.print("address of var tmp {}\n", .{&tmp});
return .{
.value = &tmp,
};
}
};
pub fn main() void {
const one = Box.one(23);
std.debug.print("box one {}\n\n", .{one});
const two = Box.two(23);
std.debug.print("box two {}\n", .{two});
}
resulting in:
> zig run mem.zig
address of parameter v u64@7ffe80c80188
box one mem.Box{ .value = u64@7ffe80c80198 }
address of var tmp u64@7ffe80c80190
box two mem.Box{ .value = u64@7ffe80c80190 }
So here, when I’m using the address of the parameter directly inside of the Box, it gets changed. Whereas if I copy the value to tmp
and use that address, it stays the same.
So I guess the compiler is doing something clever when using the address of a parameter in a function?