我正在尝试在 Zig 中分配 HashMap(u32, u1) 的二维数组:
fn alloc2d(comptime t: type, m: u32, n: u32, allocator: *Allocator) callconv(.Inline) ![][]t {
const array = try allocator.alloc([]t, m);
for (array) |_, index| {
array[index] = try allocator.alloc(t, n);
}
return array;
}
fn free2d(comptime t: type, array: [][]t, allocator: *Allocator) callconv(.Inline) void {
for (array) |_, index| {
allocator.free(array[index]);
}
allocator.free(array);
}
test "Alloc 2D Array" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
defer _ = gpa.deinit();
const HashSet = std.AutoHashMap(u32, u1);
var array = try alloc2d(*HashSet, 4, 4, allocator);
defer free2d(*HashSet, array, allocator);
for (array) |_, i| {
for (array[i]) |_, j| {
array[i][j] = &(HashSet.init(allocator));
}
}
defer {
for (array) |_, i| {
for (array[i]) |_, j| {
array[i][j].deinit();
}
}
}
}
但是,当我测试它时,调试器会抛出一个段错误。
谁能告诉我发生了什么以及如何解决它?
非常感谢!