zalloc: Use zig allocators in your c code
Summary
zalloc replaces malloc, calloc, realloc, and free in C modules with Zig allocators, enabling Zig-style memory management in C code.
View Cached Full Text
Cached at: 06/08/26, 11:17 AM
D-Berg/zalloc
Source: https://github.com/D-Berg/zalloc
Zalloc
Replace malloc, calloc, realloc and free in a c module with a zig allocator.
Usage
zig fetch --save git+https://github.com/D-Berg/zalloc.git
const zalloc = @import("zalloc");
pub fn build(b: *std.Build) !void {
//...
// add it as a dependency
const zalloc_dep = b.dependency("zalloc", .{
.optimize = optimize,
.target = target,
});
// Example c lib, shoutout to md4c
const md4c_mod = b.addModule("md4c", .{
.target = target,
.optimize = optimize,
.link_libc = true,
});
// this overwrites malloc, calloc, realloc and free in
// all c source files in the c module and will only affect that module.
zalloc.infect(md4c_mod);
// import the and link zalloc to your exe
exe_mod.addImport("zalloc", zalloc_dep.module("zalloc"));
exe_mod.linkLibrary(zalloc_dep.artifact("zalloc"));
}
const zalloc = @import("zalloc");
pub fn main(init: std.Io.Init) !void {
// Specify which allocator the c library will use
// DO this before calling any of the c functions.
// Forgetting this will lead to allocations returning null.
zalloc.allocator = init.gpa;
zalloc.io = init.io;
// ...
// now md4c will use zigs debug allocator.
const rc = md4c.md_html(
markdown.ptr,
@intCast(markdown.len),
processHtml,
null,
md4c.MD_FLAG_COLLAPSEWHITESPACE,
0,
);
if (rc != 0) return error.FailedToParseMarkdown;
}
Similar Articles
Zig Structs of Arrays (2024)
Explains how Zig's comptime and type reflection enable creating struct-of-arrays (SoA) data structures like MultiArrayList, which improve cache performance in high-performance applications.
std.Io.Writer.Allocating ate all my memory
A blog post reveals a memory over-allocation bug in Zig's std.Io.Writer.Allocating due to the `drain` function incorrectly reserving space for the splat parameter on every data slice, causing unexpected memory growth.
Zig ELF Linker Improvements Devlog
The new Zig ELF linker now supports fast incremental compilation with external libraries and C sources, enabling rebuilds in milliseconds on x86_64 Linux.
Writing a C Compiler, in Zig
A developer documents their experience building a C compiler named paella in Zig, following Nora Sandler’s tutorial series.
Inside Zig's Incremental Compilation
A Zig core team member explains the internals and usage of Zig's incremental compilation, which allows rebuilds in milliseconds by recompiling only changed code and patching it into the binary.