metasepi / postmortem

Postmortem for open-source operating systems
MIT License
1 stars 0 forks source link

Write Zig code to avoid some of bugs #30

Closed master-q closed 3 years ago

master-q commented 3 years ago

Read https://ziglang.org/documentation/master/.

master-q commented 3 years ago

https://news.ycombinator.com/item?id=17184729

Zig is memory-safe if you keep runtime checks enabled (e.g. with debug or release-safe optimization levels) but it does not have the compile-time guarantees of Rust.

Is it also true today?

master-q commented 3 years ago
const std = @import("std");

pub fn main() !void {
    var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    const ptr = &array[20];
    ptr.* += 1;
}
$ zig build-exe test.zig
./test.zig:5:23: error: index 20 outside array of size 10
    const ptr = &array[20];
                      ^
master-q commented 3 years ago
const std = @import("std");

pub fn main() !void {
    var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    const slice = array[2..20];
    slice[1] += 1;
}
$ zig build-exe test.zig
$ ./test
index out of bounds
/home/kiwamu/tmp/zig/test.zig:5:24: 0x22a934 in main (test)
    const slice = array[2..20];
                       ^

It causes a run-time error.

master-q commented 3 years ago

https://ziglang.org/documentation/master/#Integer-Overflow

If we capture compile time error, we need comptime keyword.

master-q commented 3 years ago

https://ziglang.org/documentation/master/#Division-by-Zero

Or use const variable to causes compile error.

master-q commented 3 years ago

https://ziglang.org/documentation/master/#Lifetime-and-Ownership

Above means the Zig doesn't have lifetime such as Rust's.

master-q commented 3 years ago

Umm... Finally we think that the Zig language is not suitable for this postmortem.