zig 分配器不需要 dealloc?

问题描述 投票:0回答:1

我已经使用 zig 有几天了,并开始学习分配器。据我所知,zig 没有垃圾收集器,所以像下面的代码肯定会带来错误:

const std = @import ("std");
const alloc_1 = std.heap.page_allocator;

pub fn main () !void {
    const arr = try alloc_1.alloc (u8, 3);
    arr[0] = 0;
}

我使用 valgrind 通过下一个命令来跟踪内存泄漏

valgrind --leak-check=full --track-origins=yes ./allocators
并得到这个:

==23890== Memcheck, a memory error detector
==23890== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==23890== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
==23890== Command: ./allocators
==23890== 
==23890== 
==23890== HEAP SUMMARY:
==23890==     in use at exit: 0 bytes in 0 blocks
==23890==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==23890== 
==23890== All heap blocks were freed -- no leaks are possible
==23890== 
==23890== For lists of detected and suppressed errors, rerun with: -s
==23890== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

所以基本上内存被清除,尽管我没有释放它。

memory-leaks zig
1个回答
0
投票

我不认为 valgrind 可以与 llvm 一起使用,但我不知道你可能更喜欢做类似的事情

const memory = try allocator.alloc(u8, 100);
defer allocator.free(memory);

参考:https://zig.guide/standard-library/allocators/

© www.soinside.com 2019 - 2024. All rights reserved.