Skip to content

Zig Illegal Behavior & Panics

Errors are for things that can go wrong in normal use: a missing file, bad input. But some mistakes are simply bugs: reading the fourth item of a three-item array, unwrapping a null you were sure wasn’t there. Zig calls these illegal behavior. You don’t handle them with catch; you fix the code. What Zig does when one happens depends on the build mode, and understanding that is the key to shipping Zig programs with confidence.

Here’s the most common bug in any language with arrays, the off-by-one loop. It uses <= where it should use <:

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("score {d}: {d}\n", .{ i, scores[i] });
}
}

You’ll see something like:

score 0: 10
score 1: 20
score 2: 30
thread 2973 panic: index out of bounds: index 3, len 3
main.zig:7:57: 0x11e3e14 in main (main.zig)
std.debug.print("score {d}: {d}\n", .{ i, scores[i] });
^

The array has three items, at positions 0, 1 and 2. When i reaches 3, Zig doesn’t read whatever memory happens to come after the array. It stops the program with a panic: a message saying what went wrong (index 3, len 3 is about as clear as it gets), then a stack trace pointing at the exact spot. The thread number and addresses change between runs, and there are a few more trace lines from Zig’s startup code that we’ve trimmed.

In C, this same loop would read past the end of the array without complaint, print some random number, and carry on. Bugs like that can hide for years. A panic with a line number is a bug you can fix in a minute.

Out of bounds is one kind. Here are the ones you’ll run into most, with the panic message you’ll see in a debug build. We ran each of them on Zig 0.17.1:

Mistake Example Panic message
Index or slice past the end items[i] with i >= items.len index out of bounds: index 3, len 3
Integer overflow x += 1 when x is a u8 holding 255 integer overflow
Unwrapping null opt.? when opt is null attempt to use null value
Unwrapping an error x catch unreachable when x is an error attempt to unwrap error: InvalidCharacter
Wrong union field reading .square when .circle is set access of union field 'square' while field 'circle' is active
A cast that doesn’t fit @intCast of 300 into a u8 integer does not fit in destination type
Division by zero a / b with b == 0 division by zero
Reaching unreachable else => unreachable that does run reached unreachable code

Overflow has its own lesson, Zig Integer Overflow, with five ways to avoid it. unreachable is covered in Zig Unreachable, and .? and catch unreachable in Zig Optionals and Zig Try & Catch. The language reference on illegal behavior has the full list, each with its own example.

Two from the table deserve a closer look.

A union holds one of its fields at a time. Reading a different one is illegal behavior, and Zig keeps track of which field is active so it can tell you:

const std = @import("std");
const Shape = union(enum) {
circle: f32,
square: f32,
};
pub fn main() void {
var s: Shape = .{ .circle = 2.0 };
_ = &s;
std.debug.print("side: {d}\n", .{s.square});
}

You’ll see something like:

thread 3209 panic: access of union field 'square' while field 'circle' is active
main.zig:11:39: 0x11e3df3 in main (main.zig)
std.debug.print("side: {d}\n", .{s.square});
^

_ = &s; is a small trick that stops the compiler from treating s as a constant it can check while compiling. The fix for this kind of bug is a switch on the union, which only lets you read the field that’s really there (see Zig Tagged Unions).

@intCast converts between integer types and promises the value fits. When it doesn’t:

const std = @import("std");
pub fn main() void {
var big: u32 = 300;
_ = &big;
const small: u8 = @intCast(big);
std.debug.print("{d}\n", .{small});
}

You’ll see something like:

thread 3218 panic: integer does not fit in destination type
main.zig:6:23: 0x11e3dd1 in main (main.zig)
const small: u8 = @intCast(big);
^

A u8 stops at 255, so 300 can’t fit. The same panic happens when you @intCast a negative number into an unsigned type. If the value might not fit, check first, or use std.math.cast, which returns null instead of panicking (Zig Type Casting has the details).

When the values are known at compile time, Zig doesn’t wait for the program to run. Here the index is a plain 3:

const std = @import("std");
pub fn main() void {
const scores = [_]u32{ 10, 20, 30 };
std.debug.print("score: {d}\n", .{scores[3]});
}
main.zig:5:46: error: index 3 outside array of length 3
std.debug.print("score: {d}\n", .{scores[3]});
^

This is the best case: the bug never reaches a user. That’s also why many examples in these lessons use var with _ = &x;: it forces a check at runtime so you can see the panic.

Everything so far was a debug build, the default for zig run. Zig has four build modes, and they treat illegal behavior differently:

Mode What it’s for Illegal behavior
debug Writing and testing code Checked: panic with a message
safe Shipping, with checks kept Checked: panic with a message
fast Shipping, as fast as possible Not checked: anything can happen
small Shipping, as small as possible Not checked: anything can happen

(Older code and guides call these Debug, ReleaseSafe, ReleaseFast and ReleaseSmall. Zig 0.17 renamed them, and still accepts the old names.)

In fast and small, Zig removes the safety checks to make the program faster or smaller. The compiler then assumes illegal behavior never happens and optimizes the code based on that. If it does happen, there’s no rule about what you get. Here’s the off-by-one loop from the top of this page on our Linux test machine:

Terminal window
zig run -O fast main.zig

You’ll see something like:

score 0: 10
score 1: 20
score 2: 30

followed by a crash with a segmentation fault (exit code 139). And with -O small:

score 0: 10
score 1: 20
score 2: 30
score 3: 16889707

This time it didn’t crash at all. It read memory that wasn’t part of the array and printed it as if it were a score. Same code, same bug, two different results, and neither tells you what went wrong. Another machine, Zig version or small change to the code could give something else again. C programmers know this as undefined behavior.

Some illegal behavior is unchecked, even in debug. Zig can’t insert a check for it, so it’s undefined in every mode. The big one is using memory after it’s been freed:

const std = @import("std");
pub fn main(init: std.process.Init) void {
const nums = init.gpa.alloc(u32, 4) catch return;
@memset(nums, 7);
init.gpa.free(nums);
std.debug.print("after free: {d}\n", .{nums[0]});
}

You’ll see something like:

after free: 1431655765

No panic. The slice nums still points at the old memory, and reading it gives junk (here 0x55555555, the pattern the allocator from init.gpa writes over freed memory). Returning a slice that points into a function’s local variables is the same kind of bug. Zig helps here in other ways: the allocator from init.gpa reports leaks and panics on double frees, and defer keeps frees in one obvious place. But for these bugs, the compiler can’t save you, so it’s worth reading Zig Ownership carefully.

You can override the build mode’s safety setting inside one block with @setRuntimeSafety:

const std = @import("std");
fn sumFirst(items: []const u32, n: usize) u32 {
@setRuntimeSafety(false);
var total: u32 = 0;
for (0..n) |i| total += items[i];
return total;
}
pub fn main() void {
const items = [_]u32{ 1, 2, 3 };
std.debug.print("{d}\n", .{sumFirst(&items, 3)});
}

Output:

6

Inside sumFirst, the index and overflow checks are gone, even in a debug build. If someone calls it with n = 4, you’re back to “anything can happen”. It’s meant for a hot loop that you’ve measured and tested, not for everyday code. @setRuntimeSafety(true) does the opposite: it keeps the checks in one block even in a fast build, which is a nice option for code that handles outside data.

When you write your own code, you choose how problems show up:

  • Return an error when the problem can happen even if your program is correct: the user typed something wrong, the file is missing, the network is down. The caller decides what to do.
  • Panic (with unreachable, .?, catch unreachable or @panic("message")) only when the problem means your code is wrong. There’s nothing sensible a caller could do about it.

A good test: “could a perfect program still hit this?” If yes, it’s an error. If no, it’s a bug, and a panic is the right signal. Zig Unreachable shows @panic and std.debug.assert, the tools for writing your own checks.

Fix the loop from the top of this page so it prints all three scores and doesn’t panic. Then write it a second, more Zig-like way, with a for loop that has no index at all.

Hint: the condition should be i < scores.len. A for loop over the array can’t go out of bounds.

Show solution
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("score {d}: {d}\n", .{ i, scores[i] });
}
for (scores, 0..) |score, n| {
std.debug.print("score {d}: {d}\n", .{ n, score });
}
}

Output:

score 0: 10
score 1: 20
score 2: 30
score 0: 10
score 1: 20
score 2: 30

The for version is the one to prefer: Zig handles the counting, so there’s no index to get wrong. Reach for an index only when you really need one.

Write fn toByte(n: u32) ?u8 that returns the value as a u8, or null if it doesn’t fit. Test it with 200 and 300, printing the results with {?d}.

Hint: std.math.cast(u8, n) already returns ?u8.

Show solution
const std = @import("std");
fn toByte(n: u32) ?u8 {
return std.math.cast(u8, n);
}
pub fn main() void {
std.debug.print("{?d}\n", .{toByte(200)});
std.debug.print("{?d}\n", .{toByte(300)});
}

Output:

200
null

@intCast is a promise (“this always fits”), and breaking it is illegal behavior. std.math.cast is a question (“does it fit?”), so the answer can be null. Use the question whenever the number comes from outside your code.

Write fn getScore(scores: []const u32, i: usize) !u32 that returns error.NoSuchScore instead of panicking when i is too big. Print getScore(&scores, 1) and getScore(&scores, 5) with {!d}.

Hint: compare i with scores.len before you index.

Show solution
const std = @import("std");
fn getScore(scores: []const u32, i: usize) !u32 {
if (i >= scores.len) return error.NoSuchScore;
return scores[i];
}
pub fn main() void {
const scores = [_]u32{ 10, 20, 30 };
std.debug.print("{!d}\n", .{getScore(&scores, 1)});
std.debug.print("{!d}\n", .{getScore(&scores, 5)});
}

Output:

20
error.NoSuchScore

If the index comes from a user (“show me score number 5”), a wrong value isn’t a bug in your program, so it should be an error, not a panic. The check turns illegal behavior into a normal error the caller can handle.

  • Illegal behavior is a bug like reading out of bounds, overflow, unwrapping null, or reading the wrong union field.
  • In debug and safe builds, Zig checks for it and panics with a clear message and a stack trace.
  • In fast and small, the checks are gone and anything can happen: a crash, garbage, or code that seems to work.
  • If the values are known at compile time, Zig reports the problem as a compile error instead.
  • Some illegal behavior, like use after free, can’t be checked in any mode.
  • @setRuntimeSafety turns checks off (or on) for one block. Use it rarely.
  • Errors are for problems a correct program can still meet; panics are for bugs.

Next up: Zig Custom Error Sets, designing your own errors and adding details to them.

Quick check

1. A program reads items[5] from a 3-item slice in a safe build. What happens?
2. What can happen if the same bug runs in a fast build?
3. Which of these is NOT caught by Zig's runtime safety checks?
4. A user types a line number that might be too big. How should your function react?