How to allocate in build.zig?

It’s not quite clear to me what’s the intended allocation pattern when writing build.zig. Let’s say I am writing an

pub fn build(b: *std.build.Builder) void {
   // my code here
}

Is the following correct:

  1. I can use b.allocator as my general purpose allocator, I don’t need to create my own var gpa = std.heap.GeneralPurposeAllocator(.{}){};
  2. The scope of b.allocator covers both construction of build graph (the fn build) as well as the execution of actual steps. That is, that steps can “close over” b.allocator and use it at runtime, it is not an arena scoped purely to the build
  3. In general, I don’t have to worry about freeing things. Steps don’t have deinit function, and that’s ok and by design.

Looking at the implementation:

It looks the answer is “yes, on all three counts” at least for what’s currently implemented.

And I guess the fourth “yes” question: Is a.create(T) catch @panic("OOM") the correct way to handle allocation failure in build.zig?

The relevant issue is improve std.build to set a good example of proper error handling on out of memory · Issue #8350 · ziglang/zig · GitHub which has been closed with catch @panic("OOM"); seeming to be the preferred way to handle allocation errors in build.zig.

2 Likes

Looked again at this today, and noticed that the Build struct is itself confused about memory management (or I am misreading the code).

There’s a destroy method, so it sorta tries to cleanup after itself:

But then there’s a bunch of data it forgets to cleanup:

And we are not handling allocation failure here:

I wonder if we should just go and:

  • Rename Build.allocator to Build.arena
  • Clearly document that the arena is permanent
  • Remove destroy method.
2 Likes

Agreed.

Here are a couple relevant issues:

These two phases will see some separation introduced, including potentially being executed in different processes or contexts. Point being it’s fine to use the same allocator in both, but you should not rely on the allocator being the same instance. I think it’s unlikely this constraint will ever be a problem.

2 Likes