Won't Zig in future will face the same problem with undefined in Javascript

It is illegal behavior and is caught by Valgrind:

andy@bark ~/tmp> cat test.zig
const std = @import("std");
pub fn main() void {
    var x: i32 = undefined;
    x += 2;
    std.debug.print("{d}", .{x});
}
andy@bark ~/tmp> zig build-exe test.zig -target x86_64-linux
andy@bark ~/tmp> valgrind ./test
==1375503== Memcheck, a memory error detector
==1375503== Copyright (C) 2002-2024, and GNU GPL'd, by Julian Seward et al.
==1375503== Using Valgrind-3.23.0 and LibVEX; rerun with -h for copyright info
==1375503== Command: ./test
==1375503== 
==1375503== Conditional jump or move depends on uninitialised value(s)
==1375503==    at 0x1039022: test.main (test.zig:4)
==1375503==    by 0x10389E6: callMain (start.zig:647)
==1375503==    by 0x10389E6: callMainWithArgs (start.zig:616)
==1375503==    by 0x10389E6: start.posixCallMainAndExit (start.zig:571)
==1375503==    by 0x103861D: (below main) (start.zig:271)

However Zig’s safety check currently misses it because 0xaaaaaaaa + 2 does not overflow. Often times safety checks will catch it however if you multiply or if you use it to index a slice.

Related: runtime safety for branching on undefined values and other undefined behavior caused by undefined values · Issue #63 · ziglang/zig · GitHub

8 Likes