Skip to content

Zig Error: panic: attempt to use null value

panic: attempt to use null value is not a compile error. Your program built and ran, and then a .? met a null. .? means “I’m sure this optional has a value, give it to me”, and this time you were wrong. Debug builds stop right there with a stack trace that points at the .?. The fix is to decide what should happen when the value is missing, and Zig has a tool for each choice. For the other errors in this series, see Zig Errors Explained.

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var prices: std.StringHashMapUnmanaged(u32) = .empty;
defer prices.deinit(gpa);
try prices.put(gpa, "apple", 3);
const p = prices.get("kiwi").?;
std.debug.print("kiwi costs {d}\n", .{p});
}

You’ll see something like:

thread 9999 panic: attempt to use null value
main.zig:8:33: 0x11e42ed in main (main.zig)
const p = prices.get("kiwi").?;
^

get returns ?u32: a price, or null if the key isn’t in the map. There’s no kiwi, so it returned null, and .? panicked. The caret sits on the .?. The thread number and addresses change every run, and the trace has a few more lines from Zig’s startup code below these.

An optional (?T) is a value that might be missing. Zig makes you handle the missing case before you use the value, so a plain const p: u32 = prices.get("kiwi"); doesn’t even build (see expected type ‘X’, found ‘Y’). .? is the shortcut that skips the handling: it’s the same as orelse unreachable. You’re promising the value is there. The language reference calls a broken promise an attempt to unwrap null, and shows it both while compiling and at runtime.

In debug and safe builds, Zig checks that promise and panics if it’s broken. In fast and small builds the check is gone, and a broken promise is illegal behaviour: the program carries on with garbage. So .? is fine when you know the value is there (you just put it in the map yourself), and a bug waiting to happen when the value comes from outside. Zig Optionals covers optionals from the start.

If there’s a sensible value for “missing”, use it:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var prices: std.StringHashMapUnmanaged(u32) = .empty;
defer prices.deinit(gpa);
try prices.put(gpa, "apple", 3);
const p = prices.get("kiwi") orelse 0;
std.debug.print("kiwi costs {d}\n", .{p});
}

Output:

kiwi costs 0

Only use a default when it really means something. A price of 0 for an unknown fruit might be a bug of its own; if so, use Fix 2 or 3.

if (optional) |value| runs the first block with the value inside, and else when it’s null:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var prices: std.StringHashMapUnmanaged(u32) = .empty;
defer prices.deinit(gpa);
try prices.put(gpa, "apple", 3);
for ([_][]const u8{ "apple", "kiwi" }) |fruit| {
if (prices.get(fruit)) |p| {
std.debug.print("{s} costs {d}\n", .{ fruit, p });
} else {
std.debug.print("no price for {s}\n", .{fruit});
}
}
}

Output:

apple costs 3
no price for kiwi

Inside the first block, p is a plain u32, no .? needed. This is the most common fix, and it reads well. See Zig If/Else.

If a missing value means the caller did something wrong, return an error. orelse return error.X does it in one line:

const std = @import("std");
fn priceOf(prices: std.StringHashMapUnmanaged(u32), fruit: []const u8) !u32 {
return prices.get(fruit) orelse error.UnknownFruit;
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var prices: std.StringHashMapUnmanaged(u32) = .empty;
defer prices.deinit(gpa);
try prices.put(gpa, "apple", 3);
std.debug.print("apple: {d}\n", .{try priceOf(prices, "apple")});
const kiwi = priceOf(prices, "kiwi") catch |err| {
std.debug.print("kiwi: {t}\n", .{err});
return;
};
std.debug.print("kiwi: {d}\n", .{kiwi});
}

Output:

apple: 3
kiwi: UnknownFruit

Now the caller decides: try passes the error further up, catch handles it. See Zig Errors.

Fix 4: Use while for “next item” loops

Section titled “Fix 4: Use while for “next item” loops”

Iterators return null when they’re done. Calling it.next().? in a loop panics at the end. Let while unwrap it, and the loop stops on null by itself:

const std = @import("std");
pub fn main() void {
var it = std.mem.splitScalar(u8, "a,b,c", ',');
while (it.next()) |part| {
std.debug.print("{s}\n", .{part});
}
}

Output:

a
b
c

The same pattern works for reading lines from input and for list.pop(), which returns null on an empty list. See Zig Iterators.

  • Hash map lookups: map.get(key).? for a key that isn’t there. See Zig HashMap.
  • Environment variables: init.environ_map.get("HOME").? when the variable isn’t set. See Zig Environment Variables.
  • Iterators and pop(): .? after the last item.
  • Search functions: std.mem.find(u8, text, "x").? when the text doesn’t contain it.
  • Optional fields in a struct that weren’t filled in, such as user.nickname.?.

firstWord should return the text before the first space, or the whole text if there’s no space. It panics with attempt to use null value on "zig". Fix it so the program prints hello and zig.

const std = @import("std");
fn firstWord(text: []const u8) []const u8 {
const space = std.mem.findScalar(u8, text, ' ').?;
return text[0..space];
}
pub fn main() void {
std.debug.print("{s}\n", .{firstWord("hello world")});
std.debug.print("{s}\n", .{firstWord("zig")});
}

Hint: if there’s no space, the word ends at text.len.

Show solution
const std = @import("std");
fn firstWord(text: []const u8) []const u8 {
const space = std.mem.findScalar(u8, text, ' ') orelse text.len;
return text[0..space];
}
pub fn main() void {
std.debug.print("{s}\n", .{firstWord("hello world")});
std.debug.print("{s}\n", .{firstWord("zig")});
}

Output:

hello
zig

findScalar returns null when there’s no space, and orelse text.len turns that into “the end of the text”, so the slice is the whole string.

  • panic: attempt to use null value happens at runtime: a .? met a null.
  • .? is a promise that the value is there. It’s the same as orelse unreachable.
  • Give a default with orelse, branch with if (x) |v|, or return an error with orelse return error.X.
  • Loop over iterators with while (it.next()) |item|.
  • Keep .? for cases where null would mean your own code is wrong.

Next up: Zig Exercises, small programs to practise everything so far.

Quick check

1. What does x.? mean for an optional x?
2. Which loop reads every item from an iterator safely?
3. map.get(name) might not find the name, and the caller should be told. What fits best?