Skip to content

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.

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:

10
20
30
thread 9821 panic: index out of bounds: index 3, len 3
main.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.

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 <.

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: 10
1: 20
2: 30

for (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.

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:

10
20
30

The 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 null

For 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.

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 3
main.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:

zig

A slice whose start is after its end has its own panic: start index 2 is larger than end index 1.

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.)

  • while (i <= len) instead of <.
  • items[i + 1] or items[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.

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:

5
5
10

With 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 bounds happens at runtime: you asked for a position the array or slice doesn’t have.
  • Valid positions are 0 to len - 1. index N, len N is an off-by-one.
  • Prefer for loops; in while, use i < 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’s index N outside array of length M.

Next up: attempt to use null value, the panic for unwrapping an empty optional.

Quick check

1. An array has len 5. Which index is out of bounds?
2. Which loop condition visits every valid index of items?
3. In which build modes does Zig check indexes?