Closed shaozi closed 1 week ago
return &s;
is a pointer to stack memory, after leaving init
s
is invalid and its memory is reused.
The S pointer you're returning is to a local the goes out of scope when the function exits
Also writer.any()
takes a pointer to the writer
, which also goes out of scope when the function exits.
Got it. I see. Changed to this makes it work:
const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var s = S{};
s.init(stdout);
try s.write('x');
}
const S = struct {
w: std.io.AnyWriter = undefined,
pub fn init(self: *S, w: anytype) void {
self.w = w.any();
}
pub fn write(self: *S, c: u8) !void {
try self.w.writeByte(c);
}
};
Thanks!
having struct fields default to undefined is a big code smell and in this case i'd drop the init method and do const s = S{ .w = stdout.any() };
In the future, please direct things like this to one of the community spaces first.
Zig Version
0.13.0
Steps to Reproduce and Observed Behavior
pub fn main() !void { const stdout = std.io.getStdOut().writer(); var s = init(stdout); try s.write('x'); }
fn init(w: anytype) *S { var s = S{ .w = w.any() }; return &s; } const S = struct { w: std.io.AnyWriter,
};
Expected Behavior
should not crash and output
x
to stdout.Also on 0.12.0, the error message has
possible race condition
in it. So it could be the reason.