Zig Error: panic: index out of bounds: index N, len M
panic: index out of bounds: index 3, len 3 is not a compile error. Your program built, ran, and then tried to read or write item number 3 of something that only has 3 items (numbered 0, 1 and 2). In debug builds Zig stops right there instead of reading whatever memory comes next, which is what C would do. The message tells you both numbers, so the bug is usually easy to spot. When Zig can see the bad index while compiling, you get a compile error instead, covered below. For the other errors in this series, see Zig Errors Explained.
The panic message
Section titled “The panic message”const std = @import("std");
pub fn main() void { const scores = [_]u32{ 10, 20, 30 }; var i: usize = 0; while (i <= scores.len) : (i += 1) { std.debug.print("{d}\n", .{scores[i]}); }}You’ll see something like:
102030thread 9821 panic: index out of bounds: index 3, len 3main.zig:7:42: 0x11e3e0e in main (main.zig) std.debug.print("{d}\n", .{scores[i]}); ^The loop printed three items fine, then crashed on the fourth try. index 3 is the position you asked for, len 3 is how many items there are. The caret points at the [i]. The thread number and addresses change every run, and a few more trace lines from Zig’s startup code follow; you can ignore those.
What it means
Section titled “What it means”Arrays and slices in Zig count from 0. An array with len items has positions 0 to len - 1. Asking for position len or higher is out of bounds. In debug and safe builds, Zig checks every index and panics on a bad one. The language reference lists this check under index out of bounds, with one example caught while compiling and one at runtime. In fast and small builds there’s no check, and a bad index reads or writes random memory: the kind of bug that’s very hard to find later. Zig Arrays and Zig Slices explain indexing, and Zig Illegal Behavior covers what each build mode checks.
When index equals len exactly, like here, it’s almost always an off-by-one: a <= that should be <.
How to fix it
Section titled “How to fix it”Fix 1: Let for do the counting
Section titled “Fix 1: Let for do the counting”Most index bugs go away when you don’t manage the index yourself. A for loop visits each item exactly once:
const std = @import("std");
pub fn main() void { const scores = [_]u32{ 10, 20, 30 }; for (scores, 0..) |s, i| { std.debug.print("{d}: {d}\n", .{ i, s }); }}Output:
0: 101: 202: 30for (scores) |s| gives just the items; adding 0.. also gives each position. There’s no way to step past the end. See Zig For Loops.
Fix 2: Use <, not <=
Section titled “Fix 2: Use <, not <=”If you do need a while loop, the condition for “every valid index” is i < len:
const std = @import("std");
pub fn main() void { const scores = [_]u32{ 10, 20, 30 }; var i: usize = 0; while (i < scores.len) : (i += 1) { std.debug.print("{d}\n", .{scores[i]}); }}Output:
102030The same applies to code like items[i + 1] inside a loop: when i is the last index, i + 1 is out of bounds. Stop the loop one earlier (i + 1 < items.len).
Fix 3: Check indexes that come from outside
Section titled “Fix 3: Check indexes that come from outside”When the index comes from a user, a file or a calculation, check it before you use it. Returning an optional makes “no such item” a normal answer instead of a crash:
const std = @import("std");
fn get(items: []const u32, i: usize) ?u32 { if (i >= items.len) return null; return items[i];}
pub fn main() void { const scores = [_]u32{ 10, 20, 30 }; std.debug.print("{?d} {?d}\n", .{ get(&scores, 1), get(&scores, 7) });}Output:
20 nullFor the last item, check for an empty slice first: items[items.len - 1] on an empty slice fails even earlier, with integer overflow, because 0 - 1 doesn’t fit in a usize. ArrayList has list.last(), which returns null when the list is empty.
Fix 4: Keep slice ends inside the length
Section titled “Fix 4: Keep slice ends inside the length”Slicing checks bounds too. word[0..end] with end past the length panics with the same message:
const std = @import("std");
pub fn main() void { const word: []const u8 = "zig"; var end: usize = 5; _ = &end; std.debug.print("{s}\n", .{word[0..end]});}You’ll see something like:
thread 9811 panic: index out of bounds: index 5, len 3main.zig:7:36: 0x11e3e00 in main (main.zig) std.debug.print("{s}\n", .{word[0..end]}); ^For “the first end bytes, or fewer if the string is shorter”, clamp the end with @min:
const std = @import("std");
pub fn main() void { const word: []const u8 = "zig"; var end: usize = 5; _ = &end; std.debug.print("{s}\n", .{word[0..@min(end, word.len)]});}Output:
zigA slice whose start is after its end has its own panic: start index 2 is larger than end index 1.
When Zig catches it while compiling
Section titled “When Zig catches it while compiling”If both the array and the index are known at compile time, the error comes before the program runs:
const std = @import("std");
pub fn main() void { const nums = [_]i32{ 1, 2, 3 }; std.debug.print("{d}\n", .{nums[3]});}main.zig:5:37: error: index 3 outside array of length 3 std.debug.print("{d}\n", .{nums[3]}); ^Same idea, same fix: the last valid index is 2. (That’s also why the panic examples on this page use var and _ = &end;: they stop Zig from checking the index while compiling, so you can see the runtime panic.)
Where you’ll usually see it
Section titled “Where you’ll usually see it”while (i <= len)instead of<.items[i + 1]oritems[i - 1]at the edges of a loop.- Indexes from user input or command-line arguments, without a check. See Zig CLI Arguments.
- Slicing strings with a fixed length, like
name[0..10], on shorter strings. - Reading a buffer past the part that was filled. Slice to the filled length first.
Related errors
Section titled “Related errors”- integer overflow:
len - 1on an empty slice, often found together with index bugs. - attempt to use null value: the panic you get when an optional is unwrapped with
.?and isnull. - unable to resolve comptime value: where slicing a fixed buffer (and these checks) often comes in.
- All Zig error pages: the full list.
Practice
Section titled “Practice”1. Pairs of neighbours
Section titled “1. Pairs of neighbours”This program should print the differences between neighbouring numbers: 5, 5 and 10. It panics with index out of bounds: index 4, len 4. Fix the loop.
const std = @import("std");
pub fn main() void { const nums = [_]i32{ 10, 15, 20, 30 }; var i: usize = 0; while (i < nums.len) : (i += 1) { std.debug.print("{d}\n", .{nums[i + 1] - nums[i]}); }}Hint: the last pair starts at index 2. What should the loop condition be so i + 1 stays valid?
Show solution
const std = @import("std");
pub fn main() void { const nums = [_]i32{ 10, 15, 20, 30 }; var i: usize = 0; while (i + 1 < nums.len) : (i += 1) { std.debug.print("{d}\n", .{nums[i + 1] - nums[i]}); }}Output:
5510With i + 1 < nums.len, the loop stops when i is 2, so nums[i + 1] is at most nums[3]. Writing it as i + 1 < len instead of i < len - 1 also avoids an overflow if the array is ever empty.
panic: index out of boundshappens at runtime: you asked for a position the array or slice doesn’t have.- Valid positions are
0tolen - 1.index N, len Nis an off-by-one. - Prefer
forloops; inwhile, usei < len. - Check indexes from outside first, and return an optional for “no such item”.
- Clamp slice ends with
@min(end, s.len). Known at compile time, it’sindex N outside array of length M.
Next up: attempt to use null value, the panic for unwrapping an empty optional.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Index out of bounds in the Zig language reference: the safety check and when it runs.
- Arrays in the Zig language reference: indexing and
len. - Slices in the Zig language reference: slicing with
a[start..end]. - Zig Arrays: our lesson on arrays and indexing.