对Zig中的结构列表执行Malloc操作



如何动态分配内存空间并获取指向Zig中结构列表的指针。

类似于C:

struct Foo* my_array_of_foo = (struct Foo*) malloc(10*sizeof(Foo));
const allocator: *std.mem.Allocator = std.heap.page_allocator; // this is not the best choice of allocator, see below.
const my_slice_of_foo: []Foo = try allocator.alloc(Foo, 10);
defer allocator.free(my_slice_of_foo);

这将分配一个len为10的切片。稍后可以使用allocator.free(my_slice_of_foo)释放

在zig中,数组通常表示为包含指针和项目数(struct {ptr: [*]type, len: usize}(的切片。分配器的函数.create(type)为单个值分配空间并返回指针,函数.alloc(type, count)分配连续数组并返回切片。

对于这样的任务,std.heap.page_allocator不是分配器的最佳选择。我建议使用通用分配器,它可以为您捕获内存泄漏,在出现错误后更容易找到使用方法,并更有效地使用内存:

pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(!gpa.deinit());
const allocator = &gpa.allocator;
}

在测试中,使用测试分配器是一种很好的做法,它提供了与通用分配器相同的安全功能,但由测试工具处理:

test "allocate stuff" {
const allocator = std.testing.allocator;
}

创建竞技场分配器通常也很有用。.free()对竞技场分配器不做任何操作,相反,当竞技场分配器被销毁时,所有放入竞技场分配器的东西都会同时释放。这可以使您的应用程序部分的内存管理更容易、更快。

const allocator = ... pick an allocator;
var arena_allocator = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator.deinit();
const arena = &arena_allocator.allocator;

最新更新