The docs for .toOwnedSlice
read “The caller owns the returned memory. Empties this ArrayList, Its capacity is cleared, making deinit() safe but unnecessary to call.”. However, running this test:
const std = @import("std");
const print = std.debug.print;
test ".toOwnedSlice does not seem to make deinit unnecessary" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var listOfLists = std.ArrayList([]u32).init(allocator);
try listOfLists.append(try buildAList(0, allocator));
try listOfLists.append(try buildAList(1, allocator));
print("{any}\n", .{listOfLists.toOwnedSlice()});
}
fn buildAList(val: u32, allocator: std.mem.Allocator) ![]u32 {
var list = std.ArrayList(u32).init(allocator);
try list.append(val);
return list.toOwnedSlice();
}
shows three memory leaks - two at try list.append(val);
, and one at try listOfLists.append(try buildAList(0, allocator));
, contrary to my expectations.
Unfortunately I don’t have enough Zig terminology to articulate my question any better than this, but hopefully my confusion is clear. What’s going on here that I’m misunderstanding?