by Lyngbakr · 3y ago · 0 comments
var arr = [_]u32{ 1, 2, 3, 4, 5, 6 }; // 1, 2, 3, 4, 5, 6
const slice1 = arr[1..5]; // 2, 3, 4, 5
const slice2 = slice1[1..3];
If I were to use indices out of range, presumably that would that give me a compile time error? Could I use variables as the indices and, if so, could I get a seg fault at runtime or are there some sort of guards on there?yup
$ zig test test.zig
test.zig:8:56: error: index 3 outside array of length 2
std.debug.print("\ncompile error: {d}\n", .{slice2[3]});
> Could I use variables as the indices and, if so, could I get a seg fault at runtime or are there some sort of guards on there?Bounds are checked by default:
$ zig test test.zig
test.zig:9:56: error: index 3 outside array of length 2
std.debug.print("\ncompile error: {d}\n", .{slice2[invalid_index]});
But you can disable them by building in `ReleaseFast` mode[1]Here's a test file you can use to play around with it if you like:
const std = @import("std");
test "bounds" {
var arr = [_]u32{ 1, 2, 3, 4, 5, 6 }; // 1, 2, 3, 4, 5, 6
const slice1 = arr[1..5]; // 2, 3, 4, 5
const slice2 = slice1[1..3]; // 3, 4
const invalid_index: usize = 3;
std.debug.print("\nslice2: {d} {d}\n", .{ slice2[0], slice2[1] });
std.debug.print("\ncompile error: {d}\n", .{slice2[invalid_index]});
try std.testing.expect(slice2.len == 2);
}
1: https://ziglang.org/documentation/master/#Build-ModeUnless you build in releasefast, which disables that check. There is releasesafe for a release build that keeps bounds checking panics.
Yes, if all operands are comptime-known (or comptime-length-known), bounds checks happen eagerly at compile time.
> Could I use variables as the indices and, if so, could I get a seg fault at runtime or are there some sort of guards on there?
Yes you can use variables. If they're out of range, behavior depends on the build mode:
- In Debug and ReleaseSafe, you get a guaranteed panic (which aborts the app with a stack trace)
- In ReleaseSmall and ReleaseFast, you get undefined behavior
On their discord I suggested a version of slicing that bounds checks in all modes (something like `slice?[1..5]`, syntax doesn't matter) and returns an optional slice, which is null if the bounds are out of range. But they didn't seem too keen on it. So I've been using a little wrapper function instead.