Best way to deallocate keys in StringHashMap

I’m starting to use the StringHashMap provided by the standard library. For deallocation, I’m using the below code. In this example, keys are dynamically allocated.

var pairs = std.StringHashMap(u32).init(allocator);
...
defer {
    var it = pairs.iterator();
    while (it.next()) | entry | {
        allocator.free(entry.key_ptr.*);
    }
    pairs.deinit();
}

Is the previous one the best way for memory deallocation, particularly for the keys?

1 Like

Seems fine to me. Only thing that sticks out is the ...; the defer should basically always come directly after the init.

1 Like

You’re right about the defer inmediatelly after the allocation. Thanks for your answer.