Malloc 到 Zig 中的结构列表?

the*_*uck 5 zig

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

就像在 C 中一样:

struct Foo* my_array_of_foo = (struct Foo*) malloc(10*sizeof(Foo));
Run Code Online (Sandbox Code Playgroud)

pfg*_*pfg 9

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);
Run Code Online (Sandbox Code Playgroud)

这将分配一个长度为 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;
}
Run Code Online (Sandbox Code Playgroud)

在测试中,最好使用测试分配器,它提供与通用分配器相同的安全功能,但由测试工具为您处理:

test "allocate stuff" {
    const allocator = std.testing.allocator;
}
Run Code Online (Sandbox Code Playgroud)

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

const allocator = ... pick an allocator;
var arena_allocator = std.heap.ArenaAllocator.init(allocator);
defer arena_allocator.deinit();
const arena = &arena_allocator.allocator;
Run Code Online (Sandbox Code Playgroud)