Pierre Beaucamp

Allocations as side-effects

As the old saying goes “learn concepts, not languages”. As a result, I usually try to explore something new instead of learning another flavour of C.

With this in mind, I wasn’t very excited to learn Zig. It was a pragmatic choice for a side-project that I’m working on. But to my surprise, I did learn a new concept: Memory allocations are side-effects.

If you asked me a few months ago, I would’ve told you that I was familiar with memory management. I knew to avoid heap allocations if performance is critical. But - “premature optimization is the root of all evil” - so I generally stopped worrying about it.

In Zig, that’s no longer true. It's encouraged to accept an allocator parameter if a function needs allocations. This pattern makes calls to alloc trivial to spot. Furthermore, it marks potential places for future improvements.

Haskell furst showed me the advantages of explicitly treating side-effects. With it, it became trivial to reason about functions. Zig takes this a step further with its allocator pattern. For example, you can pass a “testing” allocator in your unit-tests. This will check your code for memory leaks, among other features.

This approach to memory safety is both simple and brilliant. And as a benefit, I feel like I have learned a new concept - not an isolated language feature.