Skip to content

Instantly share code, notes, and snippets.

@rikchilvers
Last active August 5, 2021 07:54
Show Gist options
  • Select an option

  • Save rikchilvers/dfa69b73162aa54f664f36b57071b108 to your computer and use it in GitHub Desktop.

Select an option

Save rikchilvers/dfa69b73162aa54f664f36b57071b108 to your computer and use it in GitHub Desktop.
This works when run but crashes when tested. UAF? Zig bug?
const std = @import("std");
const testing = std.testing;
const print = std.debug.print;
const Node = struct {
const Self = @This();
data: u8,
children: ?std.StringHashMap(*Self) = null,
fn init(data: u8) Self {
return Self{ .data = data };
}
fn deinit(self: *Self, allocator: *std.mem.Allocator) void {
if (self.children == null) return;
var iter = self.children.?.iterator();
while (iter.next()) |kv| {
kv.value_ptr.*.deinit(allocator);
allocator.destroy(kv.value_ptr);
// allocator.destroy(kv.key_ptr);
}
self.children.?.deinit();
}
fn addChild(self: *Self, allocator: *std.mem.Allocator, data: u8) anyerror!*Self {
const newName = try std.fmt.allocPrint(allocator, "{}", .{data});
// defer allocator.free(newName);
// Make sure we have a place to store the child
if (self.children == null) {
self.children = std.StringHashMap(*Self).init(allocator);
}
var ptr = try allocator.create(Self);
ptr.* = Self.init(data);
try self.children.?.put(newName, ptr);
return ptr;
}
};
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
try testFn(allocator);
}
fn testFn(allocator: *std.mem.Allocator) anyerror!void {
var data: u8 = 0;
var n = Node.init(data);
// Child 0-1 (1)
data += 1;
_ = try n.addChild(allocator, data);
n.deinit(allocator);
}
test "init and deinit" {
try testFn(testing.allocator);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment