Skip to content

Lesson 8 of 9 · 26m

Testing, Debugging, and Fuzzing Systems Code

Use Zig tests, allocator fault injection, sanitizers, debugger workflows, and input fuzzing to expose ownership and edge-case failures before users do.

Systems code fails in the seams: allocation failure, partial writes, malformed input, integer overflow, unexpected EOF, and resource cleanup after stage two of five. Ordinary unit tests rarely hit those seams because developers test what they already believe. Zig gives you tight feedback loops, but you still have to design tests that challenge your ownership story.

Put tests next to behavior

Zig test blocks make low-friction testing normal:

test "parsePort accepts valid range" {
    try std.testing.expectEqual(@as(u16, 443), try parsePort("443"));
    try std.testing.expectError(error.Overflow, parsePort("65536"));
}

Run them through the build contract:

zig build test
zig test src/main.zig

Tests should cover boundaries, not merely examples: empty input, maximum input, one-past-maximum, malformed UTF-8, zero-length files, permission errors, and repeated invocation.

Fault injection changes what you can trust

A leaking or half-initialized structure often appears only when allocation fails. Use std.testing.allocator or a failing allocator to exercise paths:

test "builder cleans up on allocation failure" {
    var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{});
    const a = failing.allocator();
    try std.testing.expectError(error.OutOfMemory, buildPlan(a, sample_config));
}

Exact knobs vary by Zig version, but the discipline does not. Force failure at different allocation indexes and verify no leak or double-free. This is where errdefer either proves its worth or exposes its absence.

Debug builds are diagnostic tools

Zig's safety checks catch integer overflow, invalid indexing, and other undefined behavior in safety-enabled modes. Do not treat those crashes as annoyances. They are the compiler and runtime telling you that an invariant was false.

zig build -Doptimize=Debug
zig build -Doptimize=ReleaseSafe
zig build -Doptimize=ReleaseFast

ReleaseFast disables many checks for speed. ReleaseSafe is often a better production default for security-sensitive utilities until measurements prove otherwise.

Use sanitizers through C territory

When C interop or undefined behavior is involved, compiler instrumentation helps. Depending on target and Zig version, you can compile with sanitizer support or test equivalent C translation units with Clang:

zig cc -fsanitize=address,undefined -g test.c -o test-bin
zig build-exe src/main.zig -fsanitize-c

Availability and flags differ across versions, so verify with zig build-exe --help on the toolchain you ship. The important practice is not a flag; it is intentionally testing memory unsafe seams.

Fuzz parsers, not business logic theater

Any parser exposed to files, network input, or user-controlled text deserves fuzz-shaped testing. Start with structured mutations and regression cases:

test "parser regression corpus" {
    const cases = [_][]const u8{ "", "\x00", "{}", "[", "\xff\xff" };
    for (cases) |input| {
        _ = parse(input) catch continue;
    }
}

Then graduate to coverage-guided fuzzing where practical. Save every crash input as a regression test. A crash you do not preserve is a crash you will rediscover during a release.

Debug with evidence, not superstition

Use std.debug.print sparingly, but do not be ashamed of it in a small utility. For deeper issues, use gdb or lldb with debug symbols, inspect core dumps, and record exact inputs and environment. Optimized binaries are harder to debug because variables are moved, inlined, or eliminated.

Field notes

  • A test that only verifies success proves almost nothing about cleanup. Pair it with allocator leak detection and failure injection.
  • std.testing.expectError checks error identity, not user experience. Test final stderr and exit codes for CLI behavior too.
  • Timeouts, filesystem effects, and environment variables make CLI tests flaky. Isolate them in temporary directories.
  • Sanitizers and safety checks cost performance; that cost is usually cheaper than shipping memory corruption.
  • Fuzzing parsers that accept compressed or nested formats can explode input size. Bound decompression and recursion before fuzzing.
  • Debugging release crashes starts with artifact provenance: compiler version, target, optimization mode, commit, and exact input.

Was this lesson helpful?

Sign in to rate