# Idiomatic way to deinit structures with allocated memory?

**URL:** <https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640>\
**Category:** Explain\
**Created:** [September 18, 2026, 8:40am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640 "2026-09-18T08:40:29Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![psznm](https://ziggit.dev/user_avatar/ziggit.dev/psznm/32/8377_2.png) [@psznm](https://ziggit.dev/u/psznm)\
**Post date:** [September 18, 2026, 8:40am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/1 "2026-09-18T08:40:29Z")

</div>

So lets say I have a structure that only holds a pointer to an allocated memory and so the deinit is just freeing the memory and nothing else. What is the idiomatic way to do it?

```zig
pub fn deinit(self: @This(), gpa: Allocator) void {
    gpa.free(self.slice);
}

```

This is sufficient, but it hides the semantics, because one could assume the “self” parameter being passed-in may not be modified since it is passed in by value. Same would go for `*const @This()`

So it seems to show the semantics in the signature it would make sense to do

```zig
pub fn deinit(self: *@This(), gpa: Allocator) void {
    gpa.free(self.slice);
}

```

But then any variable of this instance has to be mutable if ever deinited, which is kinda annoying because then I lose semantics on the usage that I never want to mutate the variable after initialization (besides the deinit) and also It loses optimization opportunities I believe (please, correct me if I am wrong).

---

<div class="post-metadata">

**Author:** ![truly-not-taken](https://ziggit.dev/user_avatar/ziggit.dev/truly-not-taken/32/6205_2.png) [@truly-not-taken](https://ziggit.dev/u/truly-not-taken)\
**Post date:** [September 18, 2026, 9:00am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/2 "2026-09-18T09:00:18Z")

</div>

```Zig
pub fn deinit(self: *@This(), gpa: Allocator) void {
    gpa.free(self.slice);
    self.* = undefined;
}

```

---

<div class="post-metadata">

**Author:** ![pasta](https://ziggit.dev/user_avatar/ziggit.dev/pasta/32/6273_2.png) [@pasta](https://ziggit.dev/u/pasta)\
**Post date:** [September 18, 2026, 9:11am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/3 "2026-09-18T09:11:22Z")

</div>

> one could assume the “self” parameter being passed-in may not be modified since it is passed in by value. Same would go for \*const @This()

This is probably better understood as a common misconception. These have never prevented the struct from changing the values it points to (see - passing around a `std.mem.Allocator` which obviously can change internal allocator state).

Because of that I’ve generally used non-const pointers for my deinit func, because IMHO forcing call sites to use `var` to reflect that the deinit _does_ invalidate the struct (and setting it to undefined like above for safety) has always felt cleanest to me, as a `const` somewhat implies the struct doesn’t even need a deinit call.

It also has the added benefit of preventing an accidental deinit in a call site that you’ve only given a copy or a const ptr to!

---

<div class="post-metadata">

**Author:** ![floooh](https://ziggit.dev/user_avatar/ziggit.dev/floooh/32/2989_2.png) [@floooh](https://ziggit.dev/u/floooh)\
**Post date:** [September 18, 2026, 9:58am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/4 "2026-09-18T09:58:26Z")

</div>

Tbh I would avoid the scenario of such fine-grained owning pointers in structs as much as possible in the first place, because once you have such a C++ style destructor function, the next thing you’d ineviatably want is a “copy” and “move” operation, and then you’ll need to start tracking ownership and lifetime manually and before you know it you’ll start thinking that maybe refcounting wasn’t such a bad idea, and at that point you can just switch back to C++ 😉

IMHO in any language without RAII or garbage collection the best approach for simple structs is to not have any data ‘dangling off’ the struct, so that passing the struct around is always safe with a simple assignment, and a ‘destruction’ is a no-op. For complex objects, move ownership completely into a system, and use “generation-counted index handles” instead of pointers to identify an object (e.g. [Handles are the better pointers](https://floooh.github.io/2018/06/17/handles-vs-pointers.html)).

Another approach somewhere in the middle is to let arenas completely own their items. IMHO the fine-grained deallocation in deinit functions are at odds with this idea. Once you manage memory with arenas, also let the arena manage ownership and lifetime (e.g. the _arena_ owns its allocations, not some object which allocated from the arena, and all allocations in an arena share the same lifetime).

Just my 2ct 😉

---

<div class="post-metadata">

**Author:** ![ericlang](https://ziggit.dev/user_avatar/ziggit.dev/ericlang/32/8515_2.png) [@ericlang](https://ziggit.dev/u/ericlang)\
**Post date:** [September 18, 2026, 11:15am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/5 "2026-09-18T11:15:14Z")

</div>

> [@floooh](#):
>
> the best approach for simple structs is to not have any data ‘dangling off’ the struct

That is kinda understandable but still… how would you define for example an image?  
For me that would be something like

```zig
const Image = struct {
    width: u32,
    height: u32,
    pixels: []Bgra, // allocated dangling data :)
};

```

---

<div class="post-metadata">

**Author:** ![pasta](https://ziggit.dev/user_avatar/ziggit.dev/pasta/32/6273_2.png) [@pasta](https://ziggit.dev/u/pasta)\
**Post date:** [September 18, 2026, 11:32am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/6 "2026-09-18T11:32:11Z")

</div>

The key would be who owns “pixels”? The struct in this form doesn’t seem like it would need to own it at all.

---

<div class="post-metadata">

**Author:** ![floooh](https://ziggit.dev/user_avatar/ziggit.dev/floooh/32/2989_2.png) [@floooh](https://ziggit.dev/u/floooh)\
**Post date:** [September 18, 2026, 11:54am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/7 "2026-09-18T11:54:39Z")

</div>

For an `Image` object I would use an opaque handle (same way how you get opaque ‘handles’ back from 3D APIs), and the actual Image object behind the handle and all its related data would be owned by the system which created the image (and you would destroy it with an explicit destroy function, or if the handle is dangling, it would either be a no-op or a hard error).

The Image handle can be passed around by value, and there can be many handles of the same image in the wild without having to track them, since generation-counted handles have runtime dangling-safety (e.g. at the time something calls into the ‘Image system’ with an invalid handle, it will be detected that the handle is stale/invalid).

---

<div class="post-metadata">

**Author:** ![kirisoup](https://ziggit.dev/letter_avatar_proxy/v4/letter/k/ac91a4/32.png) [@kirisoup](https://ziggit.dev/u/kirisoup)\
**Post date:** [September 18, 2026, 12:34pm UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/8 "2026-09-18T12:34:14Z")

</div>

Something like this works on the master branch:

```zig
    // const Foo = struct { ...
    pub fn deinit(self: anytype, allocator: std.mem.Allocator) void {
        assert(@TypeOf(self) == Foo or @TypeOf(self.*) == Foo);
        allocator.free(self.buf);
        
        const is_mut = switch (@typeInfo(@TypeOf(self))) {
            else => false,
            .pointer => |ptr| !ptr.attrs.@"const",
        };
        if (is_mut) self.buf = undefined;
    }

```

* * *

The `self: anytype` pattern has some interesting behaviors:

```zig
// if we have
fn TypeEcho(self: anytype) type { return @TypeOf(self); }

// then, these are satisfied:
{
    var foo = ...;
    try expect(foo.TypeEcho() == *Foo);
} {
    const foo = ...;
    try expect(foo.TypeEcho() == *const Foo);
} {
    var foo = ...; // or const foo
    try expect (Foo.TypeEcho(foo) == Foo);
}

```

_Edit: oops you can’t actually call the TypeEcho thing with a runtime value, but you get the idea_

---

<div class="post-metadata">

**Author:** ![truly-not-taken](https://ziggit.dev/user_avatar/ziggit.dev/truly-not-taken/32/6205_2.png) [@truly-not-taken](https://ziggit.dev/u/truly-not-taken)\
**Post date:** [September 18, 2026, 12:58pm UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/9 "2026-09-18T12:58:44Z")

</div>

> [@ericlang](#):
>
> how would you define for example an image?

> [@floooh](#):
>
> an opaque

Like this?

```Zig
const Bgra = [4]u8;

const Image = opaque {
    const alignment = @max(@alignOf(u32), @alignOf(Bgra));
    const Pointer = *align(alignment) Image;
    const head_size = @max(@sizeOf(u32) * 2, @alignOf(Bgra));

    fn create(allocator: std.mem.Allocator, w: u32, h: u32) std.mem.Allocator.Error!Pointer {
        const size = head_size + @sizeOf(Bgra) * w * h;
        const memory = try allocator.alignedAlloc(u8, .fromByteUnits(alignment), size);
        const self: Pointer = @ptrCast(memory);
        self.width().* = w;
        self.height().* = h;
        return self;
    }

    fn destroy(self: Pointer, allocator: std.mem.Allocator) void {
        const size = head_size + @sizeOf(Bgra) * self.width().* * self.height().*;
        const ptr: [*]align(@alignOf(Bgra)) u8 = @ptrCast(self);
        allocator.free(ptr[0..size]);
    }

    fn width(self: Pointer) *u32 {
        return @ptrCast(self);
    }

    fn height(self: Pointer) *u32 {
        const ptr: [*]u32 = @ptrCast(self);
        return &ptr[1];
    }

    fn pixels(self: Pointer) []Bgra {
        const bytes: [*]align(@alignOf(Bgra)) u8 = @ptrCast(self);
        const ptr: [*]Bgra = @ptrCast(&bytes[head_size]);
        return ptr[0 .. self.width().* * self.height().*];
    }
};

test {
    var img = try Image.create(std.testing.allocator, 320, 200);
    defer img.destroy(std.testing.allocator);
    std.debug.print("width={}\nheight={}\npixels.len={}\n", .{ img.width().*, img.height().*, img.pixels().len });
}

```

---

<div class="post-metadata">

**Author:** ![floooh](https://ziggit.dev/user_avatar/ziggit.dev/floooh/32/2989_2.png) [@floooh](https://ziggit.dev/u/floooh)\
**Post date:** [September 18, 2026, 1:18pm UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/10 "2026-09-18T13:18:14Z")

</div>

No, more like this (funny, the example code is even about Images):

> **[GitHub - zig-gamedev/zpool: Generic pool & handle implementation for Zig.](https://github.com/zig-gamedev/zpool)**
>
> Generic pool & handle implementation for Zig.

---

<div class="post-metadata">

**Author:** ![psznm](https://ziggit.dev/user_avatar/ziggit.dev/psznm/32/8377_2.png) [@psznm](https://ziggit.dev/u/psznm)\
**Post date:** [September 18, 2026, 3:51pm UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/11 "2026-09-18T15:51:47Z")

</div>

> [@floooh](#):
>
> Tbh I would avoid the scenario of such fine-grained owning pointers in structs possible in the first place

Well I don’t know about that, it seems more nuanced than that to me. The structure that prompted me to ask this question doesn’t even outlive its stack (and its stack is extremely short lived). For some more context: it is for generic pre-parsed template rendering(without generics) and for storing the parameters briefly as a string instead of their raw form, so that I can pass it to the function that actually renders the template.

I know the value of handles, and I use them quite a bit in my program (in fact the parameters are rendered to local string store and given handles which is nice because it is deduplicated even if used repeatedly, and the sequence of the variables is just few bytes instead of full strings), but using them here would just either simply increase complexity for no benefit, or would waste memory for unknown amount of time. I could use arena, but then I would have an arena for just two allocations (of the string store + for the slice for storing the variable sequence) which to me sounds like its much simpler to just handle the allocations locally, so I don’t think arena is worth it either.

And no. This won’t lead to me wanting copy and move operations and refcounting.

---

<div class="post-metadata">

**Author:** ![ericlang](https://ziggit.dev/user_avatar/ziggit.dev/ericlang/32/8515_2.png) [@ericlang](https://ziggit.dev/u/ericlang)\
**Post date:** [September 18, 2026, 4:19pm UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/12 "2026-09-18T16:19:53Z")

</div>

Omg… I am a simple guy.  
(My imagehandle is just a pointer to my abovementioned struct).

---

<div class="post-metadata">

**Author:** ![floooh](https://ziggit.dev/user_avatar/ziggit.dev/floooh/32/2989_2.png) [@floooh](https://ziggit.dev/u/floooh)\
**Post date:** [September 18, 2026, 5:00pm UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/13 "2026-09-18T17:00:54Z")

</div>

> me to ask this question doesn’t even outlive its stack (and its stack is extremely short lived)

In that case I wouldn’t bother with the “struct-with-methods” approach but instead just use a bunch of local variables. Allocate and defer-free the pixels directly without caring about an “OOP wrapper” 🙂

(but even with an Image type that wraps a width, height and pixels slice you can just free the pixels directly when everything happens within a single stack frame anyway).

(I guess it’s becoming obvious that I’m not a big fan of the deinit-method pattern 😉 IMHO it lures people into the same trap as C++ destructors - e.g. building object trees which then may be expensive to destroy because they can lead to big ‘destruction cascades’, and with memory arenas there really isn’t much of a point of doing individual frees - granted of course, your use case is much simpler).

---

<div class="post-metadata">

**Author:** ![psznm](https://ziggit.dev/user_avatar/ziggit.dev/psznm/32/8377_2.png) [@psznm](https://ziggit.dev/u/psznm)\
**Post date:** [September 18, 2026, 5:28pm UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/14 "2026-09-18T17:28:54Z")

</div>

I think you are absolutely right, I could just replace the structure with a simple function. Made me think why I even have it like this and I came to two realizations. 1. I actually wanted to achieve something little different than I have (which is kinda unrelated). 2. I am quite fond of `pub fn format` for logging and debug printing. Which I can’t really do simply with a simple function because I have no writer to pass it to ( i mean I could create one myself, but that would be super inconvenient to use). Oh, and for super convenient passing it as fmt+arg to other things that would want to print. Makes me wonder if I rely on this feature more than I should.

---

<div class="post-metadata">

**Author:** ![jumpnbrownweasel](https://ziggit.dev/user_avatar/ziggit.dev/jumpnbrownweasel/32/263_2.png) [@jumpnbrownweasel](https://ziggit.dev/u/jumpnbrownweasel)\
**Post date:** [September 18, 2026, 11:10pm UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/15 "2026-09-18T23:10:29Z")

</div>

> [@floooh](#):
>
> (I guess it’s becoming obvious that I’m not a big fan of the deinit-method pattern 😉 IMHO it lures people into the same trap as C++ destructors - e.g. building object trees which then may be expensive to destroy because they can lead to big ‘destruction cascades’, and with memory arenas there really isn’t much of a point of doing individual frees - granted of course, your use case is much simpler).

Zig is not the best language for those so easily led astray. There are many cases where handles and arenas are not applicable, and the deinit pattern works great for those.

---

<div class="post-metadata">

**Author:** ![npc1054657282](https://ziggit.dev/user_avatar/ziggit.dev/npc1054657282/32/5790_2.png) [@npc1054657282](https://ziggit.dev/u/npc1054657282)\
**Post date:** [September 19, 2026, 6:51am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/16 "2026-09-19T06:51:14Z")

</div>

For me, the word `deinit` itself already represents ownership management, so it doesn’t give me that kind of misunderstanding. Sometimes I do use passing values as a metaphor for ownership transfer, but `deinit` is special.

---

<div class="post-metadata">

**Author:** ![tholmes](https://ziggit.dev/user_avatar/ziggit.dev/tholmes/32/5641_2.png) [@tholmes](https://ziggit.dev/u/tholmes)\
**Post date:** [September 19, 2026, 6:51am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/17 "2026-09-19T06:51:59Z")

</div>

```zig
/// Image offsets into pixels
var pixel_offsets: std.ArrayList(usize) = .empty;
/// Raw image data
var pixels: std.ArrayList(Bgra) = .empty;

const Image = struct{
    width: u32,
    height: u32,
    /// Index into pixel_offsets
    index: u32,

    /// Return an ephemeral view of this image's pixels, 
    /// invalidated when a new image is created.
    pub fn pixels(self: Image) []Bgra {
        return pixels.items[
            pixel_offsets.items[self.index]..
            pixel_offsets.items[self.index] + @as(usize, self.width) * @as(usize, self.height)
        ];
    }

    /// Create a new image.
    pub fn create(alc: std.mem.Allocator, pixels: [*]Bgra, width: u32, height: u32) std.mem.Allocator.Error!Image {
        const index = pixel_offsets.items.len;
        try pixel_offsets.append(alc, pixels.items.len);
        errdefer _ = pixel_offsets.pop();
        try pixels.append(alc, pixels[0..@as(usize, width) * @as(usize, height)]);
        return .{
            .width = width,
            .height = height,
            .index = index,
        };
    } 
};

/// Free all pixel data.
pub fn deinit(alc: std.mem.Allocator) void {
    pixel_offsets.deinit(alc);
    pixels.deinit(alc);
}

```

A more perfect version of this would probably use a “managed” struct type instead of a namespace with `pub var`. The benefit of using the managed struct type is that you could store the allocator as a struct field, ensuring that the same allocator is used to create and deinit all image data.

The downside of doing this is, of course, that you can’t free individual images - if you wanted something like that, you would of course need a more complicated system.

EDIT: You may notice that there’s a different way of modelling this - the `index` parameter of the image is effectually a (redundant) image ID, since the `ArrayList()` of offsets does essentially represent an `ArrayList()` of the images themselves.  
In light of that, you could:

- Store the pixel offset as part of the `Image` struct itself
- Store an `ArrayList(Image)` instead of an `ArrayList(usize)`
- Return the index into the `ArrayList(Image)` as an “Image ID” from `create()` instead of returning the image struct itself.

---

<div class="post-metadata">

**Author:** ![ericlang](https://ziggit.dev/user_avatar/ziggit.dev/ericlang/32/8515_2.png) [@ericlang](https://ziggit.dev/u/ericlang)\
**Post date:** [September 19, 2026, 8:34am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/18 "2026-09-19T08:34:27Z")

</div>

I understand. Thank you.  
Maybe even usable for my last project 🙂

---

<div class="post-metadata">

**Author:** ![gwenzek](https://ziggit.dev/user_avatar/ziggit.dev/gwenzek/32/8137_2.png) [@gwenzek](https://ziggit.dev/u/gwenzek)\
**Post date:** [September 20, 2026, 7:28am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/19 "2026-09-20T07:28:54Z")

</div>

I’m not sure what you’re achieving here? How is this better that allocating individual images? In your example allocating one image too much will trigger a resize and copy all previously allocated images, that seems like a nightmare.

You can roll out an ImagePool but it’s a bit more involved and only really worth it if your program is all about creating and destroying a lot of images.

And if you’re a library it means you imposed to the caller how to allocate images, which seems against Zig Zen.

For me writing nested deinit that call each other is indeed a code smell, you should put such “object tree” in an arena where they belong (like std.json does). But a simple struct that store a few slices is totally a right candidate for a deinit,especially if you have an `init` function that perform such allocations

---

<div class="post-metadata">

**Author:** ![ericlang](https://ziggit.dev/user_avatar/ziggit.dev/ericlang/32/8515_2.png) [@ericlang](https://ziggit.dev/u/ericlang)\
**Post date:** [September 20, 2026, 8:07am UTC](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640/20 "2026-09-20T08:07:14Z")

</div>

I think it is not better, but just an alternative for a certain use case.  
And there is nothing wrong with a struct owning allocated data.

(edit: what confuses me more in Zig is mutable / readonly access of the owning struct).

[Next page](https://ziggit.dev/t/idiomatic-way-to-deinit-structures-with-allocated-memory/17640.md?page=2)
