Hacker News new | ask | show | jobs
by n0ot 871 days ago
> If you never initialize a heap allocator, you can be confident your program will not heap allocate.

This is true for the standard library, where I can trust that no hidden allocations will be made. If I pull in a third party package, nothing guarantees that that lib won't init a new `std.heap.GeneralPurposeAllocator(...)`, right?

2 comments

No, and it would be impossible to prevent as well: obviously library code can do anything it wants, including asking the kernel for memory.

But this is one of those things which just wouldn't happen in practice: custom allocators are so embedded in the Zig philosophy that I cannot imagine competent Zig programmers writing a library that did something like this. It's just not what you do in Zig.

It's not impossible to prevent. Some languages do just that using capabilities. You can get capabilities by declaring them in your main function, for example, and only passing the capabilities you want to code downstream, such that it becomes literally impossible for any code to get IO access or allocate memory, for example, if the code is not explicitly given that capability. I believe Pony and Unison are examples of languages that do that (not for allocation, admittedly as they are both GC'd, but the concept would work in a language like Zig).
The thing you're talking about is just not possible in a low-level, runtime-less language like Zig. Like, utimately Zig. libraries need to generate arbitrary assembly to run on your architecture (like if you want to write a driver or something), so you can't stop someone from just writing a thing that does the syscalls itself.

The kind of "capabilities" style languages you are talking about almost always have either a runtime that handles the actual syscalls, or they don't have the capability to compile directly to the assembly you need, everything has to pass through some library. Zig does not fit into either category: it has no runtime, and the whole point of the language is to be a low-level C replacement.

Right, but that would be unidiomatic and the third party package should be criticized for doing that. Proper form would be for the allocator to be chosen by the user of the package, supplied as a parameter.