#Unmutated variable not detected

1 messages · Page 1 of 1 (latest)

analog cedar
#

The following code compiles, where it clearly shouldn't:

const std = @import("std");

const S = struct {
    fn f(_: *S) void {}
};

pub fn main() !void {
    const alloc = std.heap.smp_allocator;
    // The next line should be const, not var,
    // but the compiler does not complain.
    var s = try alloc.create(S);
    s.f();
}

I suspect that this might be the same issue as this one:
https://github.com/ziglang/zig/issues/25540
but I am not 100% sure, and as GitHub is closed for comments now (and on top of that, I don't have a Codeberg account yet), I'm not sure how o proceed.

GitHub

Zig Version 0.16.0-dev.699+529aa9f27 Steps to Reproduce and Observed Behavior I've run into this a few times now and thought I was going crazy. Locally, everything would be fine but CI would fa...

narrow crown
#

why exactly should this not compile?

#

the variable is "mutated" by virtue of a function being called on it that takes a mutable pointer to it

analog cedar
#

Because the variable is a pointer and the pointer cannot be mutated by that call. The call can only mutate the pointed-to object, but not the pointer itself.

#

You can also kinda verify it by replacing var with const. The code still compiles (and it shouldn't, if what you said were true).

narrow crown
#

right, i overlooked that s is a pointer. it should error, I agree

split dune
#

Unmutated variable check is intentionally done only with the AST. Lacking type information, the check couldn't know whether the variable was modified or not, so it doesn't error.

This behavior means the error is predictable, but also handles the worst cases of not being modified. Basically, this is fine.

#

How you proceed is the following: just fix your code. The compiler doesn't guarantee that all illegal behavior is prevented at compile time, and this isn't even illegal code.

crimson tulip
narrow crown
#

that const and var differentiates whether you change the pointer (aka the address), not whether you modify data the pointer points to