Defer/errdefer ways to prevent double free

Truly one of my favorite features of Zig. I’d also like a way for tests to automatically trigger every possible error, and not just error.OutOfMemory, since they can all leave memory in an invalid state, and it’s not possible to trigger every error simply by providing erroneous inputs to functions.

There’s another limitation to checkAllAllocationFailures, which is that since it works on the allocator level, you can’t use it with logic which accepts an OutOfMemory as recoverable. That’s admittedly minor and there are ways to work around it, the one time I ran into this I used builtin.is_test to return the OOM during testing and supply a default the rest of the time.

The only blocker on writing a ‘failurizer’ in userspace is the limitations on declarations in type reflection, as far as I’ve been able to work out. We can get the error set off functions, but there doesn’t seem to be a way to generate wrapped functions using comptime. It would have to be a compiler hack which added logic to the AST, and while that might even be possible right now, it’s beyond my level of understanding of Zig internals to attempt.

4 Likes