Zalloc, replace malloc and friends with a zig allocator in your c code

This library overwrites malloc, realloc, calloc and free in a c module with functions that call into a zig allocator.
Perhaps it is a really stupid idea but I thought it would be fun.

8 Likes

Not stupid!

This is so crazy, it just might work.

pub fn infect(mod: *std.Build.Module) void {
    mod.addCMacro("malloc", "zmalloc");
    mod.addCMacro("realloc", "zrealloc");
    mod.addCMacro("calloc", "zcalloc");
    mod.addCMacro("free", "zfree");
}
5 Likes

This is a pretty clever implementation.
When I was first learning Zig, I was toying around with game-development, which included creating some “Ziggified” GLFW bindings, and I was struggling to come up with a way to implement the custom GLFWallocator structure, simply because I couldn’t think of a simple way to keep track of the allocation sizes without some complicated lookup table, etc.
Seeing what you did here makes me feel dumb, it seems so obvious now to just prepend the value to the allocated memory. It is a very elegant solution to a problem that I was over-thinking.

2 Likes

Nah you’re not dumb. Did the same thing as you did for tree-sitters custom allocator. Stored the info using a hashmap(usize, usize). Wasn’t the best solution but atleast it found a mem leak which I actually for once wasn’t the root cause of (kind of).

Thank you! Funny to see a VERY similar solution to mine. Glad I’m not the only one obsessed with controlling memory. Initially just called them by their c names but that screwed things up with threading as zig std lib uses c_allocator and c_raw_allocator (don’t remember the exact names) for creating the threads which causes it to call my free on pointers which was not allocated by my malloc.