Severe Memory Leak on MacOS #36533

Open
opened 2026-08-16 16:52:55 +02:00 by zargor · 3 comments

Zig Version

0.17.0-dev.1770+5d7cf3f34

Steps to Reproduce, Observed Behavior, and Expected Behavior

Hello, I am on MacOS and noticed that there is a severe memory leak with Zig in general:
Command for all the following code: zig run test.zig

Simplest memory leak I could achieve:

const std = @import("std");

pub fn main(init: std.process.Init) !void {
    while (true) {
        const buffer = try init.gpa.alloc(u8, 1024 * 1024);
        init.gpa.free(buffer);
    }
}

Using the std.heap.page_allocator "fixes" the issue.
In this case the smp_allocator seems to fix the issue too.

std.Io issues

Originally, I stumbled upon this issue while playing around with the std.Io interface.
In the example below, even the smp_allocator has a memory leak of around 0.2 MB per second:

const std = @import("std");

pub fn main() !void {
    var threaded = std.Io.Threaded.init(std.heap.smp_allocator, .{});
    const io = threaded.io();

    while (true) {
        var group: std.Io.Group = .init;

        group.async(io, dummy, .{});

        try group.await(io);
    }
}

fn dummy() void {}

Using page_allocator here fixes the issue too.

I am unfortunately not that deep into low level memory management debugging yet to know what I could do to further debug this myself.

I booted up a Linux x86_64 VM and tried the code (the std.Io one) there and it seems to work fine there, so I guess this is a MacOS specific issue 🤔

My System

❯ sysctl kern.version
kern.version: Darwin Kernel Version 25.6.0: Sat Jul 11 15:26:21 PDT 2026; root:xnu-12377.161.13~4/RELEASE_ARM64_T6000

Tested zig versions: 0.16 and 0.17.0-dev.1767+63cfe88f0 and 0.17.0-dev.1770+5d7cf3f34


Below an image what it looked like in Activity Monitor after a couple of seconds with the std.Io leak AND the debug allocator that I got from std.process.Init.io :

image

### Zig Version 0.17.0-dev.1770+5d7cf3f34 ### Steps to Reproduce, Observed Behavior, and Expected Behavior Hello, I am on MacOS and noticed that there is a severe memory leak with Zig in general: Command for all the following code: `zig run test.zig` ### Simplest memory leak I could achieve: ```zig const std = @import("std"); pub fn main(init: std.process.Init) !void { while (true) { const buffer = try init.gpa.alloc(u8, 1024 * 1024); init.gpa.free(buffer); } } ``` Using the `std.heap.page_allocator` "fixes" the issue. In this case the `smp_allocator` seems to fix the issue too. # std.Io issues Originally, I stumbled upon this issue while playing around with the `std.Io` interface. In the example below, even the `smp_allocator` has a memory leak of around 0.2 MB per second: ```zig const std = @import("std"); pub fn main() !void { var threaded = std.Io.Threaded.init(std.heap.smp_allocator, .{}); const io = threaded.io(); while (true) { var group: std.Io.Group = .init; group.async(io, dummy, .{}); try group.await(io); } } fn dummy() void {} ``` Using `page_allocator` here fixes the issue too. I am unfortunately not that deep into low level memory management debugging yet to know what I could do to further debug this myself. I booted up a Linux x86_64 VM and tried the code (the std.Io one) there and it seems to work fine there, so I guess this is a MacOS specific issue 🤔 ### My System ``` ❯ sysctl kern.version kern.version: Darwin Kernel Version 25.6.0: Sat Jul 11 15:26:21 PDT 2026; root:xnu-12377.161.13~4/RELEASE_ARM64_T6000 ``` Tested zig versions: `0.16` and `0.17.0-dev.1767+63cfe88f0` and `0.17.0-dev.1770+5d7cf3f34` ------- Below an image what it looked like in Activity Monitor after a couple of seconds with the std.Io leak **AND the debug allocator that I got from `std.process.Init.io`** : ![image](/attachments/ef4fa12a-5a20-4d09-ad22-7a0e56a2ead0)
image.png
112 KiB
Contributor

If you wanted to take a look further, based on what you’ve written and the logic in start.zig it seems like you’re seeing the behavior of std.heap.SafeAllocator, which does not appear to be macOS-specific in any way.

If you wanted to take a look further, based on what you’ve written and the logic in `start.zig` it seems like you’re seeing the behavior of `std.heap.SafeAllocator`, which does not appear to be macOS-specific in any way.

Just a guess, but for the first example note that the standard allocator std.heap.SafeAllocator contains safety mechanisms in debug build modes (which zig run defaults to if no other -O [mode] is given), f.e. tracking to prevent double-frees.

  • Have you tried other build modes?
  • Maybe try turning off safety features one-by-one and see whether the issue persists?
    (I suspect that in particular the "Virtual Memory Size" in your screenshot being 416.65 GB could be an artifact of freed addresses being marked as "don't reuse" to the OS - but that's just a guess as well.)

Memory usage probably still shouldn't grow unbounded... not sure where a limit would currently be configured. (Maybe safety data would be released/reused once an actual error.OutOfMemory is encountered from the backing allocator? Though that might still be undesirable / too late on systems with overcommit?)

I don't think this explains a leak in the std.Io example though.

Just a guess, but for the first example note that the standard allocator [`std.heap.SafeAllocator`](https://codeberg.org/ziglang/zig/src/branch/master/lib/std/heap/SafeAllocator.zig) contains safety mechanisms in debug build modes (which `zig run` defaults to if no other `-O [mode]` is given), f.e. tracking to prevent double-frees. - Have you tried other build modes? - Maybe try turning off safety features one-by-one and see whether the issue persists? (I suspect that in particular the "Virtual Memory Size" in your screenshot being 416.65 GB could be an artifact of freed addresses being marked as "don't reuse" to the OS - but that's just a guess as well.) Memory usage probably still shouldn't grow unbounded... not sure where a limit would currently be configured. (Maybe safety data would be released/reused once an actual `error.OutOfMemory` is encountered from the backing allocator? Though that might still be undesirable / too late on systems with overcommit?) I don't think this explains a leak in the `std.Io` example though.
alexrp added this to the Urgent milestone 2026-08-17 08:21:55 +02:00
Contributor

The leaked memory (at least in the first example) comes from capturing the stack traces of each allocation(/deallocation?). There are two issues here. The first is the lack of .deinit which I fixed in the PR. It makes the number of frees roughly match the number of allocations (minus some small constant).

There is also a second issue and I don't know what is the best way to fix it. lib/std/debug/SelfInfo/MachO.zig uses std.debug.getDebugInfoAllocator() which returns a global arena allocator by default. MachO.zig correctly frees the memory, however, the arena only respects free if the last allocation is freed, so the memory ends up never being freed. I didn't look why this doesn't happen on other architectures.

You can uncomment the if statement at the beginning of getDebugInfoAllocator to see the function where the memory is allocated. If you make getDebugInfoAllocator return a different allocator (for example smp_allocator), the leak is fully fixed.

const std = @import("std");
const Allocator = std.mem.Allocator;
const Alignment = std.mem.Alignment;

pub const debug = struct {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    const allocator = arena.allocator();
    var recursive = false;
    var alloc_count: usize = 0;
    var free_count: usize = 0;

    fn alloc(_: *anyopaque, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8 {
        const result = allocator.rawAlloc(len, alignment, ret_addr);
        if (result != null) alloc_count += 1;

        std.log.debug("alloc {d} ({d}/{d})", .{ len, free_count, alloc_count });
        std.log.debug("capacity: {d}", .{arena.queryCapacity()});
        return result;
    }

    fn resize(_: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool {
        std.log.debug("resize {d} -> {d}", .{ memory.len, new_len });
        defer std.log.debug("capacity: {d}", .{arena.queryCapacity()});
        return allocator.rawResize(memory, alignment, new_len, ret_addr);
    }

    fn remap(_: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
        std.log.debug("remap {d} -> {d}", .{ memory.len, new_len });
        defer std.log.debug("capacity: {d}", .{arena.queryCapacity()});
        return allocator.rawRemap(memory, alignment, new_len, ret_addr);
    }

    fn free(_: *anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) void {
        free_count += 1;
        std.log.debug("free {d} ({d}/{d})", .{ memory.len, free_count, alloc_count });
        defer std.log.debug("capacity: {d}", .{arena.queryCapacity()});
        return allocator.rawFree(memory, alignment, ret_addr);
    }

    pub fn getDebugInfoAllocator() Allocator {
        // if (!recursive) {
        //     recursive = true;
        //     std.debug.dumpCurrentStackTrace(.{});
        //     recursive = false;
        // }

        return .{
            .ptr = undefined,
            .vtable = &.{
                .alloc = &alloc,
                .resize = &resize,
                .remap = &remap,
                .free = &free,
            },
        };
    }
};

pub fn main(init: std.process.Init) !void {
    while (true) {
        const buffer = try init.gpa.alloc(u8, 1024 * 1024);
        init.gpa.free(buffer);
    }
}
The leaked memory (at least in the first example) comes from capturing the stack traces of each allocation(/deallocation?). There are two issues here. The first is the lack of `.deinit` which I fixed in the PR. It makes the number of frees roughly match the number of allocations (minus some small constant). There is also a second issue and I don't know what is the best way to fix it. [`lib/std/debug/SelfInfo/MachO.zig`](https://codeberg.org/ziglang/zig/src/commit/6716bf52e70791104caf057af3fece674f0ac3dd/lib/std/debug/SelfInfo/MachO.zig) uses `std.debug.getDebugInfoAllocator()` which returns a global arena allocator by default. `MachO.zig` correctly frees the memory, however, the arena only respects `free` if the last allocation is freed, so the memory ends up never being freed. I didn't look why this doesn't happen on other architectures. You can uncomment the if statement at the beginning of `getDebugInfoAllocator` to see the function where the memory is allocated. If you make `getDebugInfoAllocator` return a different allocator (for example smp_allocator), the leak is fully fixed. ```zig const std = @import("std"); const Allocator = std.mem.Allocator; const Alignment = std.mem.Alignment; pub const debug = struct { var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); const allocator = arena.allocator(); var recursive = false; var alloc_count: usize = 0; var free_count: usize = 0; fn alloc(_: *anyopaque, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8 { const result = allocator.rawAlloc(len, alignment, ret_addr); if (result != null) alloc_count += 1; std.log.debug("alloc {d} ({d}/{d})", .{ len, free_count, alloc_count }); std.log.debug("capacity: {d}", .{arena.queryCapacity()}); return result; } fn resize(_: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool { std.log.debug("resize {d} -> {d}", .{ memory.len, new_len }); defer std.log.debug("capacity: {d}", .{arena.queryCapacity()}); return allocator.rawResize(memory, alignment, new_len, ret_addr); } fn remap(_: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8 { std.log.debug("remap {d} -> {d}", .{ memory.len, new_len }); defer std.log.debug("capacity: {d}", .{arena.queryCapacity()}); return allocator.rawRemap(memory, alignment, new_len, ret_addr); } fn free(_: *anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) void { free_count += 1; std.log.debug("free {d} ({d}/{d})", .{ memory.len, free_count, alloc_count }); defer std.log.debug("capacity: {d}", .{arena.queryCapacity()}); return allocator.rawFree(memory, alignment, ret_addr); } pub fn getDebugInfoAllocator() Allocator { // if (!recursive) { // recursive = true; // std.debug.dumpCurrentStackTrace(.{}); // recursive = false; // } return .{ .ptr = undefined, .vtable = &.{ .alloc = &alloc, .resize = &resize, .remap = &remap, .free = &free, }, }; } }; pub fn main(init: std.process.Init) !void { while (true) { const buffer = try init.gpa.alloc(u8, 1024 * 1024); init.gpa.free(buffer); } } ```
Sign in to join this conversation.
No milestone
No assignees
4 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
ziglang/zig#36533
No description provided.