Error C Allocator is only available when linking against libc

Hello,
I am on Alpine Linux trying to get a zig program with either c_allocator or raw_c_allocator to work. I installed zig version 0.13.0 through the package manager. A few months back it worked, but now it seems like zig does not recognize I have libc, the native os is Alpine Linux.
Terminal Output:

rw /tmp zig run abcd.zig
/usr/lib/zig/std/heap.zig:38:13: error: C allocator is only available when linking against libc
            @compileError("C allocator is only available when linking against libc");
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/lib/zig/std/c/linux.zig:295:12: error: dependency on libc must be explicitly specified in the build command
pub extern "c" fn malloc_usable_size(?*const anyopaque) usize;
           ^~~
/usr/lib/zig/std/c/linux.zig:294:12: error: dependency on libc must be explicitly specified in the build command
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
           ^~~
/usr/lib/zig/std/c.zig:1732:12: error: dependency on libc must be explicitly specified in the build command
pub extern "c" fn free(?*anyopaque) void;
           ^~~
rw /tmp cat abcd.zig
const std = @import("std");

pub fn main() !void {
    const allocator = std.heap.c_allocator;
    const message = "Hello, Zig!";
    const buffer = try allocator.alloc(u8, message.len);
    defer allocator.free(buffer);

    std.debug.print("Allocated string: {s}\n", .{buffer});
}
rw /tmp uname -a
Linux smile 6.12.13-0-lts #1-Alpine SMP PREEMPT_DYNAMIC 2025-02-10 21:47:33 x86_64 Linux

Does anyone know how to fix this without specifying the target explicitly? Would love to here an explanation, because I do not understand it.

Just do zig run abcd.zig -lc
The c library needs to be linked explicitly.

1 Like

Thanks, can you explain further why this is the case?

Most simple Zig programs don’t need the C standard library, that’s why it’s an opt-in feature.
The only reasons why you’d need is if you are linking against a C library that depends C standard library or I guess if you want the C allocator.

But most Zig programs don’t use the C allocator, and I would also recommend you to use the GeneralPurposeAllocator(or DebugAllocator as of Zig 0.14) instead since it gives you more safety like leak-checking, double free detection, and even use-after-free detection.

3 Likes