Member-only story

Gotchas when Doing Zig Programming (v0.7)

A report back from the land of Zig and the dangers that lurk there

Erik Engheim
7 min readNov 7, 2020

So I have been spending some time familiarizing myself with the Zig programming language.

Since we are still not in version 1.0, there are bound to be some bumps in the road. So this is me documenting some of the challenges I faced.

When Do I Get the Address?

On of the first things I naturally do in my Zig programs is to create an allocator to pass to all the functions which need to allocate memory. I use the GeneralPurposeAllocator which is good for debugging. Perhaps too good, I found its complaints a bit annoying for small test programs where I was totally fine with leaking memory all over the place. But I digress.

One thing I initially felt very uncertain about was when I would seek to obtain an address. If you look at the example below we simply get the value for the gpa and dir variable:

const std = @import("std");

pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var allocator: *std.mem.Allocator = &gpa.allocator;

const dir: Dir = std.fs.cwd();
}

However the allocator is a pointer. How do you know when to get a pointer? Here are some simple rules to keep in mind:

  1. If you are not providing an allocator to a function, then it also will not be allocating anything…

--

--

Erik Engheim
Erik Engheim

Written by Erik Engheim

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

Responses (1)