Replies: 2 comments
-
const std = @import("std");
pub const Scode = [8]u8;
pub const Sname = []const u8;
pub const ScodeNameMap = std.StringHashMap(Sname);
const scodes = [_][6]u8{
[_]u8{ '6', '0', '0', '0', '0', '1' },
[_]u8{ '6', '0', '0', '0', '0', '2' },
[_]u8{ '6', '0', '0', '0', '0', '3' },
[_]u8{ '6', '0', '0', '0', '0', '4' },
[_]u8{ '6', '0', '0', '0', '0', '5' },
[_]u8{ '6', '0', '0', '0', '0', '6' },
[_]u8{ '6', '0', '0', '0', '0', '7' },
[_]u8{ '6', '0', '0', '0', '0', '8' },
[_]u8{ '6', '0', '0', '0', '0', '9' },
};
fn getScode(allocator: std.mem.Allocator, str1: []const u8, str2: []const u8) ![]const u8 {
const buff_len = str1.len + str2.len;
var buff = try allocator.alloc(u8, buff_len);
@memcpy(buff[0..str1.len], str1);
@memcpy(buff[str1.len..buff_len], str2);
return buff;
}
test "test memory free" {
const allocator = std.testing.allocator;
var res = ScodeNameMap.init(allocator);
// https://ziglang.org/documentation/master/std/#std.hash_map.StringHashMap
// > Builtin hashmap for strings as keys.
// > Key memory is managed by the caller.
// > Keys and values will not automatically be freed.
// https://ziglang.org/documentation/master/std/#std.hash_map.HashMap.deinit
// > Release the backing array and invalidate this map.
// > This does not deinit keys, values, or the context!
// > If your keys or values need to be released, ensure that that is done before calling this function.
defer res.deinit();
std.debug.print("\n", .{});
for (0..9) |i| {
const scode = try getScode(allocator, "sh", &scodes[i]);
std.debug.print(" => i {d} scode {s}\n", .{ i, scode });
try res.put(scode, scode);
}
std.debug.print("\nres count {d}\n\n", .{res.count()});
var it = res.iterator();
while (it.next()) |kv| {
allocator.free(kv.key_ptr.*);
}
} $ zig test string_hash_map.zig
Test [1/1] string_hash_map.test.test memory free...
=> i 0 scode sh600001
=> i 1 scode sh600002
=> i 2 scode sh600003
=> i 3 scode sh600004
=> i 4 scode sh600005
=> i 5 scode sh600006
=> i 6 scode sh600007
=> i 7 scode sh600008
=> i 8 scode sh600009
res count 9
All 1 tests passed. |
Beta Was this translation helpful? Give feedback.
0 replies
-
谢谢啊,我这里理解似乎有问题。我在 lib/std/hash_map.zig 看到下面代码:
谢谢啊。搜一下相关内容看看先。 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
本来是想要解析一个 xls 文件,然后 将其中的数据创建一个 StringHashMap ,但在 free 创建的 string 的时候出现个问题,前面 6 次循环运行正确 free,第七次 会报错。报错如下:
为了方便debug【避免使用 xls 解析相关的 libxls c代码】另外写了个测试用的 demo,也会同样的错误。没有思路跟进了。敬请指教。 ^-^
代码如下:
Beta Was this translation helpful? Give feedback.
All reactions