# Defer/errdefer ways to prevent double free

**URL:** <https://ziggit.dev/t/defer-errdefer-ways-to-prevent-double-free/6983>\
**Category:** Help\
**Tags:** language\
**Created:** [November 23, 2024, 8:05pm UTC](https://ziggit.dev/t/defer-errdefer-ways-to-prevent-double-free/6983 "2024-11-23T20:05:28Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![mnemnion](https://ziggit.dev/user_avatar/ziggit.dev/mnemnion/32/2478_2.png) [@mnemnion](https://ziggit.dev/u/mnemnion)\
**Post date:** [November 24, 2024, 6:18pm UTC](https://ziggit.dev/t/defer-errdefer-ways-to-prevent-double-free/6983/6 "2024-11-24T18:18:14Z")

</div>

> [@Sze](#):
>
> But another good way to prevent double free is to use [std.testing.checkAllAllocationFailures](https://ziglang.org/documentation/master/std/#std.testing.checkAllAllocationFailures) to test your code for errors in its allocation logic.

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.

---

_[View the full topic](https://ziggit.dev/t/defer-errdefer-ways-to-prevent-double-free/6983)._
