Allocators from C to Zig
19 points by asb
19 points by asb
btw, the Allocator in Zig kind of makes functions “coloured”.
You have red functions that take an allocator parameter, and blue functions that don’t. A red function can call another red function by forwarding the allocator. But a blue function cannot easily call a red one.
A blue function can instantiate an allocator if it needs one. For example:
var arena_instance: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena_instance.deinit();
const arena = arena_instance.allocator();
redFunc(arena, ...);
It's just considered good Zig style not to do that if you're writing a library for other people to use, and instead accept an allocator for functions that need it.
I have never had this be an issue in practise, and I have been using Zig for years. I disagree that this is comparable to function coloring.
Yes, like you can instantiate an executor to run an async function from a sync function. “Function colouring” can mean different things to different people, but I agree it’s not necessarily a bad thing.
Such a blue function that wants to allocate memory really should be red 😅
Mostly the objection IMHO would be that the explicitness of passing around the allocator interface to use is "opt in": nothing prevents a blue function from passing an allocator of its choice to a red function, even if this means using an inappropriate allocator for the program (say, using a heap allocator when the rest of the program is using an arena allocator).
In fact, every Zig program has at least one such blue-to-red call chain: the main function sets up the allocator it wants to use, and passes that around to red functions.