# SafeAllocator

**URL:** <https://ziggit.dev/t/safeallocator/18651>\
**Category:** Help\
**Tags:** language\
**Created:** [November 30, 2026, 9:50pm UTC](https://ziggit.dev/t/safeallocator/18651 "2026-11-30T21:50:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ericlang](https://ziggit.dev/user_avatar/ziggit.dev/ericlang/32/8515_2.png) [@ericlang](https://ziggit.dev/u/ericlang)\
**Post date:** [November 30, 2026, 9:50pm UTC](https://ziggit.dev/t/safeallocator/18651/1 "2026-11-30T21:50:34Z")

</div>

In my code for zig 0.15.2 I had this (incredibly ugly) code to define one global allocator.

```zig
pub const is_debug: bool = builtin.mode == .debug;
const DebugAllocator = std.heap.DebugAllocator(.{});
var da = if (is_debug) DebugAllocator.init else void;
pub const gpa: std.mem.Allocator = if (is_debug) da.allocator() else std.heap.smp_allocator;

```

But it works and reports memory leaks at `deinit().`.

Now moved to 0.17.1 and can’t get my head wrapped around the SafeAllocator.

How can I define my `pub const gpa` in the same way?  
And how could I code it less ugly?  
And is SafeAllocator actually a std.mem.Allocator? That I find difficult to read.

---

<div class="post-metadata">

**Author:** ![pzittlau](https://ziggit.dev/letter_avatar_proxy/v4/letter/p/ecae2f/32.png) [@pzittlau](https://ziggit.dev/u/pzittlau)\
**Post date:** [November 30, 2026, 11:19pm UTC](https://ziggit.dev/t/safeallocator/18651/2 "2026-11-30T23:19:00Z")

</div>

In `0.16+` you can get an allocator by using the [juicy main](https://ziglang.org/download/0.16.0/release-notes.html#Juicy-Main) like this:

```zig
pub fn main(init: std.process.Init) !void {
    const gpa = init.gpa;
    const io = init.io;
    // ...
}

```

The leak checking is then done automatically for you. There is also other stuff in there.

The `gpa` that is provided is determined as follows:

```zig
const gpa = if (use_safe_allocator)
        safe_allocator.allocator()
    else if (builtin.link_libc)
        std.heap.c_allocator
    else if (is_wasm)
        std.heap.wasm_allocator
    else if (!builtin.single_threaded)
        std.heap.smp_allocator
    else
        comptime unreachable;

```

The `SafeAllocator` is afaik basically like a light version of the `DebugAllocator`(which is similar to the old `GeneralPurposeAllocator` in before `0.14` times) that tracks a bit less.

You of course don’t have to use it and can just define the `DebugAllocator` like you did before. I just copy-pasted your snippet and it seemed to work.  
Or you can define your own `SafeAllocator`:

```zig
var gpa_instance = std.heap.SafeAllocator.init(std.heap.page_allocator, .{});
pub const gpa = gpa_instance.allocator();

```
