Which Memory Bugs Does Zig Catch?

In Why Zig Over C for Systems Programming the section about what Zig does not fix was one paragraph. I wrote there that Zig does not stop you from using memory after you free it or from keeping a pointer to a stack variable that no longer exists. Some readers of the Hacker News discussion pointed out that this is the part where Rust is ahead of both C and Zig.

They are right, so I wrote a small program for each of the following cases:

  1. Reading memory after freeing it.
  2. Writing to memory after freeing it.
  3. Freeing the same memory twice.
  4. Keeping a pointer to a stack variable that no longer exists.
  5. Keeping a pointer to an element of an ArrayList that grew afterwards.

Then I ran them to see what Zig says about each one. All the code was run on a Mac with Zig 0.17.1. I shortened the stack traces to keep the output short. Zig has four build modes and I use three of them here. The debug mode is the default, the safe mode optimizes the code and keeps the safety checks and the fast mode turns the checks off.

Reading after free Link to heading

The first program frees a string and then prints it:

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;

    const name = try allocator.dupe(u8, "mihalis");
    allocator.free(name);
    std.debug.print("after free: {s}\n", .{name});
    std.debug.print("first byte: 0x{x}\n", .{name[0]});
}
$ zig run uaf.zig
after free: UUUUUUU
first byte: 0x55
$ echo $?
0

This is a bug. After the call to free() the memory no longer belongs to name and the program must not read it, yet the compiler accepts the program and it runs to the end with an exit code of 0. In the debug and safe modes init.gpa is std.heap.SafeAllocator, which I described in Allocators in Zig: Which One and When. In the debug mode it fills the memory that I free with the byte 0x55 (the letter U) and it does not give the same memory to a later allocation. That gives me a wrong value that is easy to recognize but Zig does not report the bug in any way. In the safe mode the bytes are 0xaa. In the fast mode the allocator is a different one and the program printed 0x7 and a few bytes that are not text.

With a bigger allocation the result changes. The next program allocates 1 MB, frees it and reads its first byte:

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;

    const big = try allocator.alloc(u8, 1024 * 1024);
    @memset(big, 'a');
    allocator.free(big);
    std.debug.print("first byte: 0x{x}\n", .{big[0]});
}
$ zig run big.zig
Segmentation fault at address 0x100614000
big.zig:9:49: 0x100497534 in main (big)
    std.debug.print("first byte: 0x{x}\n", .{big[0]});
                                                ^

The program stops at the line of the read in the debug and safe modes because the allocator had already returned those pages to the Operating System. In the fast mode the same program printed first byte: 0x0 and exited with 0.

Writing after free Link to heading

The second program writes to the string after freeing it:

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;

    const name = try allocator.dupe(u8, "mihalis");
    allocator.free(name);
    name[0] = 'M';
    std.debug.print("done\n", .{});
}
$ zig run waf.zig
done
thread 1294751 panic: write after free at *102a9a288
original alloc of [addr: 102a9a288, len: 7 (0x7) align: 1]:
waf.zig:6:36: 0x1029501e3 in main (waf)
    const name = try allocator.dupe(u8, "mihalis");
                                   ^
free:
waf.zig:7:19: 0x10295022f in main (waf)
    allocator.free(name);
                  ^

This time Zig finds the bug, although not at the line that has it. The program prints done first and the panic comes when main() returns. At that point the allocator looks at the memory that was freed and finds a byte that is no longer 0x55. The report says where the memory was allocated and where it was freed but not where the write happened, so I still have to look for line 8 myself. This check exists in the debug mode only. In the safe and fast modes the program printed done and exited with 0.

Double free Link to heading

The third program frees the same string twice, which is the bug that Zig handles best:

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;

    const name = try allocator.dupe(u8, "mihalis");
    allocator.free(name);
    allocator.free(name);
}
$ zig run dfree.zig
thread 1293675 panic: double free of [addr: 104672288, len: 7 (0x7) align: 1]
alloc:
dfree.zig:6:36: 0x10450746f in main (dfree)
    const name = try allocator.dupe(u8, "mihalis");
                                   ^
first free:
dfree.zig:7:19: 0x1045074bb in main (dfree)
    allocator.free(name);
                  ^
second free:
dfree.zig:8:19: 0x1045074d7 in main (dfree)
    allocator.free(name);
                  ^

The program stops at the second free() and the report has the three lines that I need. In the safe mode it stops with the same message but the stack traces are empty. In the fast mode the program printed nothing and exited with 0, which does not mean that nothing happened to the heap.

A pointer to a stack variable Link to heading

Here I have to correct my first post. Zig 0.17 does stop the simplest form of this bug at compile time. In the fourth program the makeName() function returns the address of its own local array:

const std = @import("std");

fn makeName() []const u8 {
    var buf: [8]u8 = undefined;
    @memcpy(&buf, "mihalis!");
    return &buf;
}

fn other() void {
    var noise: [64]u8 = undefined;
    @memset(&noise, 'x');
    std.mem.doNotOptimizeAway(&noise);
}

pub fn main() void {
    const name = makeName();
    other();
    std.debug.print("{s}\n", .{name});
}
$ zig run stack.zig
stack.zig:6:13: error: returning address of expired local variable 'buf'
    return &buf;
            ^~~

The check is easy to get past without meaning to. The next version is the same program with one change in makeName(), where the slice goes into a variable before the function returns it. This time the compiler says nothing:

const std = @import("std");

fn makeName() []const u8 {
    var buf: [8]u8 = undefined;
    @memcpy(&buf, "mihalis!");
    const name: []const u8 = buf[0..];
    return name;
}

fn other() void {
    var noise: [64]u8 = undefined;
    @memset(&noise, 'x');
    std.mem.doNotOptimizeAway(&noise);
}

pub fn main() void {
    const name = makeName();
    other();
    std.debug.print("{s}\n", .{name});
}
$ zig run stack.zig
xxxxxxxx

The buf array lives in the stack frame of makeName(). When that function returns, the other() function uses the same part of the stack for its own array and name now points to eight x characters. The program exited with 0 in the debug mode and in the fast mode, where it printed bytes that are not text. In the safe mode it stopped with panic: @memcpy arguments alias. That panic comes from inside std.debug.print(), at the line that copies the bytes of name to its output buffer, so it is a result of the bug but it says nothing about makeName(). There is no allocator involved, so nothing at run time looks for this bug. The same thing happens when I store a pointer to a local variable in a structure that lives longer than the function.

A pointer into an ArrayList Link to heading

The last bug does not look like one when you read the code. I take a pointer to the first element of a list and then I add more elements:

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;

    var list: std.ArrayList(u32) = .empty;
    defer list.deinit(allocator);

    try list.append(allocator, 1);
    const first = &list.items[0];
    for (2..10_000) |i| try list.append(allocator, @intCast(i));

    first.* = 42;
    std.debug.print("first = {d}, items[0] = {d}\n", .{ first.*, list.items[0] });
}
$ zig run list.zig
first = 42, items[0] = 1
thread 1295254 panic: write after free at *104c56288

When the list needs more room it allocates a bigger block, copies the elements and frees the old block. The first pointer still points to the old block, so the 42 never reaches the list. In the debug mode I get the same write after free report as before when the program ends. In the safe and fast modes the program printed the first line only and exited with 0. When I tried it with 100 elements instead of 10,000 in the debug and safe modes, the list grew without moving, both values were 42 and there was no report, so a bug like this can stay hidden until the data gets bigger. The same thing happens with a pointer to a value of a hash map after the map grows.

Finding them Link to heading

I run my programs in the debug mode with init.gpa for as long as I can because that is where most of the reports above come from. I also put the code that allocates in tests. Inside a test block std.testing.allocator does the same checks, so the read after free from the first program fails the following test, which compares the string with what it should be:

const std = @import("std");

test "use after free" {
    const allocator = std.testing.allocator;
    const name = try allocator.dupe(u8, "mihalis");
    allocator.free(name);
    try std.testing.expectEqualStrings("mihalis", name);
}
$ zig test uaf_test.zig

====== expected this output: =========
mihalis␃

======== instead found this: =========
UUUUUUU␃

======================================
First difference occurs on line 1:
expected:
mihalis
^ ('\x6d')
found:
UUUUUUU
^ ('\x55')
1/1 uaf_test.test.use after free...FAIL (TestExpectedEqual)
lib/zig/std/testing.zig:696:9: 0x100ee6917 in expectEqualStrings (test)
        return error.TestExpectedEqual;
        ^
uaf_test.zig:7:5: 0x100ee6b2f in test.use after free (test)
    try std.testing.expectEqualStrings("mihalis", name);
    ^
0 passed; 0 skipped; 1 failed.
error: the following test command failed with exit code 1:
.cache/zig/o/304dafbc/test --seed=0x11396fd6

The test fails at the first byte because it expected m and found the U that the allocator wrote over the freed memory. Unlike the first program, which exited with 0, the zig test command exits with 1.

For the list bug I keep the index of an element and not a pointer to it when the list can still grow. The index stays correct after the list moves to a bigger block because list.items always points to the current one:

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;

    var list: std.ArrayList(u32) = .empty;
    defer list.deinit(allocator);

    try list.append(allocator, 1);
    const first: usize = 0;
    for (2..10_000) |i| try list.append(allocator, @intCast(i));

    list.items[first] = 42;
    std.debug.print("items[0] = {d}\n", .{list.items[first]});
}
$ zig run list_fixed.zig
items[0] = 42

For the stack bug I let the caller pass the buffer, which is what many functions of the Standard Library do. The array now lives in the stack frame of main(), so it is still there when makeName() returns and the call to other() cannot write over it:

const std = @import("std");

fn makeName(buf: []u8) []const u8 {
    const name = "mihalis!";
    @memcpy(buf[0..name.len], name);
    return buf[0..name.len];
}

fn other() void {
    var noise: [64]u8 = undefined;
    @memset(&noise, 'x');
    std.mem.doNotOptimizeAway(&noise);
}

pub fn main() void {
    var buf: [8]u8 = undefined;
    const name = makeName(&buf);
    other();
    std.debug.print("{s}\n", .{name});
}
$ zig run stack_fixed.zig
mihalis!

Both programs print the same output in the debug, safe and fast modes and exit with 0. An arena helps with the bugs that have to do with free(), as there is one call that frees everything and no single allocation that I can free too early or twice.

Conclusion Link to heading

Zig catches some of these bugs and only at run time, in the debug mode and with the right allocator. The same programs written in safe Rust do not compile. I knew that when I chose Zig and I still choose it but I think it is better to see the bugs run than to read one paragraph that says they exist.

Happy coding in Zig!

Want to learn Zig? Look at my book Systems Programming with Zig.