# Corrupted AutoHashMap?

**URL:** <https://ziggit.dev/t/corrupted-autohashmap/18105>\
**Category:** Help\
**Tags:** language\
**Created:** [October 26, 2026, 11:58am UTC](https://ziggit.dev/t/corrupted-autohashmap/18105 "2026-10-26T11:58:38Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![devanbenz](https://ziggit.dev/user_avatar/ziggit.dev/devanbenz/32/10433_2.png) [@devanbenz](https://ziggit.dev/u/devanbenz)\
**Post date:** [October 26, 2026, 11:58am UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/1 "2026-10-26T11:58:38Z")

</div>

Hey all, new to Zig and attempting to port a few of my other projects to the language. I’m running in to an issue while attempting to use an `AutoHashMap` as a member on a struct. Here is the code:

```C
const NodeType = enum { Root, Inner, Leaf };

const Node = struct {
    allocator: std.mem.Allocator,
    node_type: NodeType,
    key_map: *std.AutoHashMap(i32, []u8),
    child_node: ?*Node,

    pub fn init(allocator: std.mem.Allocator, node_type: NodeType) @This() {
        var key_map = std.AutoHashMap(i32, []u8).init(allocator);
        const map = &key_map;
        return Node{ .allocator = allocator, .node_type = node_type, .key_map = map, .child_node = null };
    }

    pub fn deinit(self: @This()) void {
        var it = self.key_map.valueIterator();
        while (it.next()) |value_ptr| {
            self.allocator.free(value_ptr.*);
        }
    }

    pub fn get(self: @This(), key: i32) ?[]u8 {
        return self.key_map.*.get(key);
    }

    pub fn insert(self: @This(), key: i32, value: []u8) !void {
        try self.key_map.put(key, value);
    }
};

```

Using the following test:

```c
test "basic node test" {
    const allocator = std.testing.allocator;
    const node = Node.init(allocator, NodeType.Root);
    defer node.deinit();

    const data = try allocator.alloc(u8, DEFAULT_PAGE_SIZE);
    @memset(data, 10);
    try node.insert(0, data);
}

```

While running this I’m seeing the following:

```zig
thread 7643268 panic: reached unreachable code
/Users/devan/.zvm/0.17.0/lib/std/debug.zig:442:14: 0x1000969e3 in assert (test)
    if (!ok) unreachable; // assertion failure
             ^
/Users/devan/.zvm/0.17.0/lib/std/debug.zig:1870:15: 0x1000bc637 in lock (test)
        assert(l.state == .unlocked);
              ^
/Users/devan/.zvm/0.17.0/lib/std/hash_map.zig:1116:44: 0x1001c7e0f in getOrPutContextAdapted__func_999 (test)
                self.pointer_stability.lock();
                                           ^
/Users/devan/.zvm/0.17.0/lib/std/hash_map.zig:1103:56: 0x1001c7b93 in getOrPutContext (test)
            const gop = try self.getOrPutContextAdapted(allocator, key, ctx, ctx);
                                                       ^
/Users/devan/.zvm/0.17.0/lib/std/hash_map.zig:1029:52: 0x1001c799f in putContext (test)
            const result = try self.getOrPutContext(allocator, key, ctx);
                                                   ^
/Users/devan/.zvm/0.17.0/lib/std/hash_map.zig:324:45: 0x1001c78d3 in put (test)
            return self.unmanaged.putContext(self.allocator, key, value, self.ctx);
                                            ^
/Users/devan/Documents/Projects/zig-tree/src/root.zig:35:29: 0x1001c7403 in insert (test)
        try self.key_map.put(key, value);
                            ^
/Users/devan/Documents/Projects/zig-tree/src/root.zig:68:20: 0x1001c75db in test.basic btree test (test)
    try node.insert(0, data);
                   ^
/Users/devan/.zvm/0.17.0/lib/compiler/test_runner.zig:295:25: 0x1001a31c3 in mainTerminal (test)
        if (test_fn.func()) |_| {
                        ^
/Users/devan/.zvm/0.17.0/lib/compiler/test_runner.zig:74:28: 0x1001a2ca3 in main (test)
        return mainTerminal(init);
                           ^
/Users/devan/.zvm/0.17.0/lib/std/start.zig:789:88: 0x1001a0bd3 in callMain (test)
    if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
                                                                                       ^
???:?:?: 0x19cf09d53 in start (/usr/lib/dyld)
error: the following test command terminated with signal ABRT:
.zig-cache/o/d3dbf24e49389327f0244c523c2762b1/test --seed=0x9391a1ee

```

I’m wondering what I’m doing wrong? Is it idiomatic to put pointers as field types in structs or can that lead to problems?

---

<div class="post-metadata">

**Author:** ![vulpesx](https://ziggit.dev/user_avatar/ziggit.dev/vulpesx/32/3989_2.png) [@vulpesx](https://ziggit.dev/u/vulpesx)\
**Post date:** [October 26, 2026, 12:02pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/2 "2026-10-26T12:02:09Z")

</div>

> [@devanbenz](#):
>
> ```zig
> pub fn init(allocator: std.mem.Allocator, node_type: NodeType) @This() {
> var key_map = std.AutoHashMap(i32, []u8).init(allocator);
> const map = &key_map;
> return Node{ .allocator = allocator, .node_type = node_type, .key_map = map, .child_node = null };
> }
> 
> ```

`map` points to stack memory, store the hashmap directly instead of via a pointer.

I’m guessing you did this after not being able to mutate it in the other functions, just make their `self` parameter a pointer.

---

<div class="post-metadata">

**Author:** ![Southporter](https://ziggit.dev/user_avatar/ziggit.dev/southporter/32/2500_2.png) [@Southporter](https://ziggit.dev/u/Southporter)\
**Post date:** [October 26, 2026, 12:04pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/3 "2026-10-26T12:04:18Z")

</div>

> [@devanbenz](#):
>
> ```zig
> pub fn init(allocator: std.mem.Allocator, node_type: NodeType) @This() {
> var key_map = std.AutoHashMap(i32, []u8).init(allocator);
> const map = &key_map;
> return Node{ .allocator = allocator, .node_type = node_type, .key_map = map, .child_node = null };
> }
> 
> ```

The problem is here. You are creating a stack based AutoHashMap and then capturing a pointer to the stack variable. When your `init` function returns, that stack variable is reused and the pointer is invalid.

If you want to store a pointer like that, you will need to create it on the heap using your allocator.

I _think_ that you are fine to just put it without the pointer in your Node though. The struct is copyable in the sense that it points to the data created by init and so you should be fine to copy it.

---

<div class="post-metadata">

**Author:** ![devanbenz](https://ziggit.dev/user_avatar/ziggit.dev/devanbenz/32/10433_2.png) [@devanbenz](https://ziggit.dev/u/devanbenz)\
**Post date:** [October 26, 2026, 12:06pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/4 "2026-10-26T12:06:53Z")

</div>

Ah @vulpesx and @Southporter, so, even though I’m passing in an `std.mem.Allocator` to the hashmap it gets created as a stack variable? I guess I assumed (and should have checked) that it gets created on the heap using the allocator I pass it 🤔 Interesting, that makes sense though. Thanks! I’ll update this thread with the fix to confirm.

---

<div class="post-metadata">

**Author:** ![Southporter](https://ziggit.dev/user_avatar/ziggit.dev/southporter/32/2500_2.png) [@Southporter](https://ziggit.dev/u/Southporter)\
**Post date:** [October 26, 2026, 12:07pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/5 "2026-10-26T12:07:33Z")

</div>

The hashmap container is on the stack, the arrays backing the map are on the heap.

---

<div class="post-metadata">

**Author:** ![vulpesx](https://ziggit.dev/user_avatar/ziggit.dev/vulpesx/32/3989_2.png) [@vulpesx](https://ziggit.dev/u/vulpesx)\
**Post date:** [October 26, 2026, 12:10pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/6 "2026-10-26T12:10:28Z")

</div>

`init` would return a pointer if it was heap allocated, and usually such functions are called `create`

It doesn’t actually do any allocations (unless you do `initWithCapacity`), it just stores the allocator in a field so that future allocations don’t require you to pass an allocator.

Containers that store their allocator are called “managed”; But std is moving away from “managed” being the default and will probably remove them all together.

If you use the `AutoHashMapUnamanged` you wont have to pass an allocator, or even call an `init` function, instead it has a constant called `empty`, similar to what the array list uses (which is “unmanaged” by default as of 0.15)

---

<div class="post-metadata">

**Author:** ![devanbenz](https://ziggit.dev/user_avatar/ziggit.dev/devanbenz/32/10433_2.png) [@devanbenz](https://ziggit.dev/u/devanbenz)\
**Post date:** [October 26, 2026, 12:26pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/7 "2026-10-26T12:26:56Z")

</div>

Thanks, that worked:

```c
const NodeType = enum { Root, Inner, Leaf };

const Node = struct {
    allocator: std.mem.Allocator,
    node_type: NodeType,
    key_map: std.AutoHashMap(i32, []u8),
    child_node: ?*Node,

    pub fn init(allocator: std.mem.Allocator, node_type: NodeType) @This() {
        const key_map = std.AutoHashMap(i32, []u8).init(allocator);
        return Node{ .allocator = allocator, .node_type = node_type, .key_map = key_map, .child_node = null };
    }

    pub fn deinit(self: *@This()) void {
        var it = self.key_map.valueIterator();
        while (it.next()) |value_ptr| {
            self.allocator.free(value_ptr.*);
        }
        self.key_map.deinit();
    }

    pub fn get(self: @This(), key: i32) ?[]u8 {
        return self.key_map.get(key);
    }

    pub fn insert(self: *@This(), key: i32, value: []u8) !void {
        try self.key_map.put(key, value);
    }
};

```

If I were to create the `AutoHashMap` on the heap though, how would that be done?

Like this?

```c
    pub fn init(allocator: std.mem.Allocator, node_type: NodeType) @This() {
        var key_map = try allocator.create(std.AutoHashMap(i32, []u8));
        key_map = std.AutoHashMap(i32, []u8).init(allocator);
        return Node{ .allocator = allocator, .node_type = node_type, .key_map = key_map, .child_node = null };
    }

```

EDIT: I tried and that did not work 😆

---

<div class="post-metadata">

**Author:** ![vulpesx](https://ziggit.dev/user_avatar/ziggit.dev/vulpesx/32/3989_2.png) [@vulpesx](https://ziggit.dev/u/vulpesx)\
**Post date:** [October 26, 2026, 12:31pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/8 "2026-10-26T12:31:34Z")

</div>

> [@devanbenz](#):
>
> If I were to create the `AutoHashMap` on the heap though, how would that be done?
> 
> Like this?
> 
> ```c
> pub fn init(allocator: std.mem.Allocator, node_type: NodeType) @This() {
> var key_map = try allocator.create(std.AutoHashMap(i32, []u8));
> key_map = std.AutoHashMap(i32, []u8).init(allocator);
> return Node{ .allocator = allocator, .node_type = node_type, .key_map = key_map, .child_node = null };
> }
> 
> ```
> 
> EDIT: I tried and that did not work 😆

Right idea, you just missed that to write to a pointer you need to dereference it `.*`

Also you can avoid typing the generic type again, with just `.init(allocator)`.  
And ofc, don’t forget that you’d need to make the field a pointer again.

---

<div class="post-metadata">

**Author:** ![devanbenz](https://ziggit.dev/user_avatar/ziggit.dev/devanbenz/32/10433_2.png) [@devanbenz](https://ziggit.dev/u/devanbenz)\
**Post date:** [October 27, 2026, 1:34am UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/9 "2026-10-27T01:34:59Z")

</div>

EDIT: I figured it out, had to read a bit more about `std.mem.Allocator` but I found that for objects created using `Allocator.create()` I’m supposed to use `Allocator.destroy()`

This works as expected:

```c
    pub fn deinit(self: @This()) void {
        var it = self.key_map.*.valueIterator();
        while (it.next()) |value_ptr| {
            self.allocator.free(value_ptr.*);
        }
        self.key_map.deinit();
        self.allocator.destroy(self.key_map);
    }

```

Does this seem to be idiomatic Zig? Storing pointers on structs?

* * *

Coming back to this, I want to better understand how to accomplish this. I’ve gone ahead and implemented code like so:

```C
const NodeType = enum { Root, Inner, Leaf };

const Node = struct {
    allocator: std.mem.Allocator,
    node_type: NodeType,
    key_map: *std.AutoHashMap(i32, []u8),
    child_node: ?*Node,

    pub fn init(allocator: std.mem.Allocator, node_type: NodeType) !@This() {
        const key_map = try allocator.create(std.AutoHashMap(i32, []u8));
        key_map.* = .init(allocator);
        return Node{ .allocator = allocator, .node_type = node_type, .key_map = key_map, .child_node = null };
    }

    pub fn deinit(self: @This()) void {
        var it = self.key_map.*.valueIterator();
        while (it.next()) |value_ptr| {
            self.allocator.free(value_ptr.*);
        }
        self.key_map.deinit();
    }

    pub fn get(self: @This(), key: i32) ?[]u8 {
        return self.key_map.get(key);
    }

    pub fn insert(self: @This(), key: i32, value: []u8) !void {
        try self.key_map.put(key, value);
    }
};

```

I’m seeing a memory leak though

```zig
[SafeAllocator] (err): leaked [addr: 104a6c010, len: 40 (0x28) align: 8] allocated at:
/Users/devan/Documents/Projects/zig-tree/src/root.zig:18:45: 0x10493b3ff in init (test)
        const key_map = try allocator.create(std.AutoHashMap(i32, []u8));
                                            ^
/Users/devan/Documents/Projects/zig-tree/src/root.zig:64:29: 0x10493b66f in test.basic btree test (test)
    var node = try Node.init(allocator, NodeType.Root);
                            ^
/Users/devan/.zvm/0.17.0/lib/compiler/test_runner.zig:295:25: 0x1049171c3 in mainTerminal (test)
        if (test_fn.func()) |_| {
                        ^
/Users/devan/.zvm/0.17.0/lib/compiler/test_runner.zig:74:28: 0x104916ca3 in main (test)
        return mainTerminal(init);
                           ^
/Users/devan/.zvm/0.17.0/lib/std/start.zig:789:88: 0x104914bd3 in callMain (test)
    if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
                                                                                       ^
???:?:?: 0x19cf09d53 in start (/usr/lib/dyld)

All 1 tests passed.
1 errors were logged.
1 tests leaked memory.
error: the following test command failed with exit code 1:
.zig-cache/o/a892c71b5f44cf23ca815b7c51e6dc76/test --seed=0xc86c0c8b

```

I also tried to free the `key_map`

```c
    pub fn deinit(self: @This()) void {
        var it = self.key_map.*.valueIterator();
        while (it.next()) |value_ptr| {
            self.allocator.free(value_ptr.*);
        }
        self.allocator.free(self.key_map.*);
    }

```

But am seeing:

```zig
/Users/devan/.zvm/0.17.0/lib/std/mem/Allocator.zig:469:50: error: access of union field 'pointer' while field 'struct' is active
    const slice_info = @typeInfo(@TypeOf(memory)).pointer;
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~
/Users/devan/.zvm/0.17.0/lib/std/lang.zig:640:18: note: union declared here
pub const Type = union(enum) {
                 ^ ~~~~
referenced by:
    deinit: src/root.zig:28:28
    test.basic btree test: src/root.zig:65:22

```

I also tried to set `pub fn deinit(self: *This())` still with no luck. Any suggestions? Still wrapping my head around how to read Zig errors successfully lol.

---

<div class="post-metadata">

**Author:** ![JacobCrabill](https://ziggit.dev/user_avatar/ziggit.dev/jacobcrabill/32/1316_2.png) [@JacobCrabill](https://ziggit.dev/u/JacobCrabill)\
**Post date:** [October 27, 2026, 2:02am UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/10 "2026-10-27T02:02:09Z")

</div>

Glad you figured out the `create`/`destroy` pairing - zig’s `create`/`destroy` vs `alloc`/`free` are equivalent to C++'s `new`/`delete` vs. `malloc`/`free`.

> [@devanbenz](#):
>
> Does this seem to be idiomatic Zig? Storing pointers on structs?

If the object must be heap-allocated for whatever reason, or you need a pointer to some shared resource, then yes, storing a pointer is normal. However, in this specific case, I see no reason to heap-allocate the hash map - you would likely be better off leaving it on the stack (just in terms of avoiding unnecessary heap allocations and avoiding the possibility of a whole range of possible memory bugs, as you’ve already discovered 🙂 ).

(I would also double-tap the recommendation to use the `*Unmanaged` variants of the `std` data types in general)

---

<div class="post-metadata">

**Author:** ![vulpesx](https://ziggit.dev/user_avatar/ziggit.dev/vulpesx/32/3989_2.png) [@vulpesx](https://ziggit.dev/u/vulpesx)\
**Post date:** [October 27, 2026, 2:32am UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/11 "2026-10-27T02:32:18Z")

</div>

I do question why you are freeing the map values in that types `deinit` as `insert` puts them in verbatim, so there is an implicit requirement that the caller pass a value that is allocated with the same allocator.

There is a common idiom to put `Owned` in the function name to indicate a transfer of memory ownership (responsibility to free) one way or another, like `insertOwned`, or an example from std, `std.ArrayList.toOwnedSlice()`.

Alternatively you could have `insert` duplicate the value to ensure that it is heap allocated, and owned by the type.

Or you could have both :D.

Also, you can improve how you free the values, one way is to use an `AutoArrayHashMap`, which iterates over the values much more efficiently as it uses a dense array, whereas then non-array hashmap uses a sparse array.

But the most efficient would be to have the values allocated with an arena so you can free them all at once, without even iterating the map.

---

<div class="post-metadata">

**Author:** ![devanbenz](https://ziggit.dev/user_avatar/ziggit.dev/devanbenz/32/10433_2.png) [@devanbenz](https://ziggit.dev/u/devanbenz)\
**Post date:** [October 27, 2026, 12:16pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/12 "2026-10-27T12:16:52Z")

</div>

> [@vulpesx](#):
>
> But the most efficient would be to have the values allocated with an arena so you can free them all at once, without even iterating the map.

That makes sense. So my thoughts here are that since these `Node` structs will be created as a root inside a parent `Btree` struct I could just have an arena allocator on my `Btree` struct that can be used by `Node`s. In that case I don’t pass in a generic `std.mem.Allocator` but instead create the arena allocator inside the `Btree`?

> [@JacobCrabill](#):
>
> However, in this specific case, I see no reason to heap-allocate the hash map - you would likely be better off leaving it on the stack (just in terms of avoiding unnecessary heap allocations and avoiding the possibility of a whole range of possible memory bugs, as you’ve already discovered 🙂 )

Thanks, that definitely makes sense. When I leave it on the stack and utilize it like here: [Corrupted AutoHashMap? - #7 by devanbenz](https://ziggit.dev/t/corrupted-autohashmap/18105/7) does it create copies of the hashmap? I guess I could debug through the code and check.

> [@vulpesx](#):
>
> Also, you can improve how you free the values, one way is to use an `AutoArrayHashMap`, which iterates over the values much more efficiently as it uses a dense array, whereas then non-array hashmap uses a sparse array.

I’ll take a look at this, is there an `Unmanaged` version as well? I guess I could also just check in the docs lol.

EDIT: There is: [Zig Documentation](https://ziglang.org/documentation/0.12.0/std/#std.array_hash_map.AutoArrayHashMapUnmanaged)

---

<div class="post-metadata">

**Author:** ![vulpesx](https://ziggit.dev/user_avatar/ziggit.dev/vulpesx/32/3989_2.png) [@vulpesx](https://ziggit.dev/u/vulpesx)\
**Post date:** [October 27, 2026, 12:25pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/13 "2026-10-27T12:25:00Z")

</div>

> [@devanbenz](#):
>
> In that case I don’t pass in a generic `std.mem.Allocator` but instead create the arena allocator inside the `Btree`?

the arena still needs a backing allocator

> [@devanbenz](#):
>
> When I leave it on the stack and utilize it like here: [Corrupted AutoHashMap? - #7 by devanbenz](https://ziggit.dev/t/corrupted-autohashmap/18105/7) does it create copies of the hashmap?

yes, but since its in a node in a tree it should be being used via a pointer most of the time anyway.

And in other situations just always pass by pointer like you would any other type that needs mutations shared across other code that uses it.

> [@devanbenz](#):
>
> I’ll take a look at this, is there an `Unmanaged` version as well? I guess I could also just check in the docs lol.

yes, and not only is it already the default, the managed version has been removed.  
The `Unmanaged` alias still exists, but is deprecated in favour of `std.array_has_map.Auto`

---

<div class="post-metadata">

**Author:** ![devanbenz](https://ziggit.dev/user_avatar/ziggit.dev/devanbenz/32/10433_2.png) [@devanbenz](https://ziggit.dev/u/devanbenz)\
**Post date:** [October 27, 2026, 1:01pm UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/14 "2026-10-27T13:01:09Z")

</div>

> [@vulpesx](#):
>
> the arena still needs a backing allocator

So for example in my `init` function I require passing in a `std.mem.Allocator` so when I pass the `std.testing.allocator` in as the backing allocator that’s not an arena one, would I just sub an arena one?

---

<div class="post-metadata">

**Author:** ![vulpesx](https://ziggit.dev/user_avatar/ziggit.dev/vulpesx/32/3989_2.png) [@vulpesx](https://ziggit.dev/u/vulpesx)\
**Post date:** [October 28, 2026, 12:36am UTC](https://ziggit.dev/t/corrupted-autohashmap/18105/15 "2026-10-28T00:36:23Z")

</div>

Yeah you can make an arena; though I am not sure if you want one for the whole tree, or one for each node.
