Corrupted AutoHashMap?

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:

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:

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:

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?

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.

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.

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 :thinking: Interesting, that makes sense though. Thanks! I’ll update this thread with the fix to confirm.

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

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)

Thanks, that worked:

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?

    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 :laughing:

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.

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:

    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:

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

[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

    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:

/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.

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.

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 :slight_smile: ).

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

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.

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 Nodes. In that case I don’t pass in a generic std.mem.Allocator but instead create the arena allocator inside the Btree?

Thanks, that definitely makes sense. When I leave it on the stack and utilize it like here: Corrupted AutoHashMap? - #7 by devanbenz does it create copies of the hashmap? I guess I could debug through the code and check.

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

the arena still needs a backing allocator

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.

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

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?

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