-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Warn/error when returning stack variable references #14156
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
Comments
|
Is it expected to work again or should that be considered forbidden in the future? |
I expect it to work once the pass-by-reference optimization is fixed, but since it is just an optimization the compiler is allowed to not do it so you should still take a pointer. |
Ok. And "bonus" thing, I notice that this works: fn Bytes(comptime len: usize) type {
return struct {
const Self = @This();
buffer: [len]u8,
pub fn set(self: *Self, value: []const u8) !void {
if (self.buffer.len != value.len) {
return error.BadLength;
}
mem.copy(u8, &self.buffer, value);
}
pub fn get(self: *const Self, key: []const u8) ![]const u8 {
_ = key;
return &self.buffer;
}
};
}
pub const Id = Bytes(32);
pub const Msg = union(MsgType) {
t0: Id,
t1: Id,
const Self = @This();
pub fn set(self: *Self, key: []const u8, value: []const u8) !void {
switch (self.*) {
inline else => |*inner| try inner.set(key, value),
}
}
pub fn get(self: *const Self, key: []const u8) ![]const u8 {
switch (self.*) {
inline else => |*inner| return try inner.get(key),
}
}
};
But if I do (
It still compiles but I get the bug again. Shouldn't that be a compile error? Edit: just to clarify, I get why I get the bug (still returning stack values) and why it works (it get coerced), but it feels like the compiler could "do something" to help me catch that. |
Not with the current semantics but if you have some idea on how that could be improved feel free to make a proposal. |
Thanks for the taking the time to explain. I will think about how the developer experience could be improved in this case. |
Zig Version
0.11.0-dev.1022+af197d4954
Steps to Reproduce and Observed Behavior
Consider the following code:
It fails with:
The first weird thing is that the two printed addresses are not the same (a0 and a1) so there must be some array copying involved.
The second problem is the test failing.
If I remove the access like this:
the test passes.
Expected Behavior
Test should succeed.
The text was updated successfully, but these errors were encountered: