logoalt Hacker News

ponkpandayesterday at 8:18 PM2 repliesview on HN

Not original commenter but the reality with zig is a little in between being simply convention vs. a language requirement. Is it a language requirement? no.

However, there's no global allocator in zig. You simply cannot call the language's equivalent of malloc() because it doesn't exist - at least not as a global symbol. That leaves you with three choices: 1) Define a global allocator; is a valid choice and would make a zig program more like C, C++ or Rust in terms of not having to think about scope-level allocation patterns 2) Pass an allocator into that scope (this is the community convention) 3) Create/instantiate an allocator itself inside that scope

(1) would be valid, though may not be idiomatic; global allocator like malloc becomes an opt-in

(2) Expensive and inefficient for most scopes, though not all.

(3) cheap, idiomatic but potential for noise/boilerplate


Replies

dnauticstoday at 6:27 AM

> However, there's no global allocator in zig. You simply cannot call the language's equivalent of malloc() because it doesn't exist - at least not as a global symbol.

I mean std.heap.page_allocator is global, and there's only the one, and you can call it from wherever (just as you can malloc). Same with std.heap. c_allocator, which is... malloc! you can also create your own global allocator.

Don't do this in libraries ofc or the ghost of Andrew Kelly will haunt you in hour sleep.

articulatepangtoday at 1:23 AM

I think you switched 2 and 3.