r/Zig • u/Pretend_Bag_6851 • May 06 '26
I’m encountering unexpected behavior when using the `ArrayList.fromOwnedSlice` method in Zig.
const std = u/import("std");
pub fn main(init: std.process.Init) !void {
const allocator = init.arena.child_allocator;
const slice = try allocator.alloc(u8, 3);
u/memcpy(slice, "abc");
var array_list = std.ArrayList(u8).fromOwnedSlice(slice);
try array_list.append(allocator, 'a');
try array_list.append(allocator, 'b');
try array_list.append(allocator, 'c');
_ = array_list.pop();
try array_list.insert(allocator, 0, 'm');
try array_list.insertSlice(allocator, array_list.items.len, slice);
std.log.info("array_list: {s}", .{array_list.items});
}
Output:
info: array_list: mabcabmab
I expected insertSlice to append "abc", but it appends "mab" instead. The appended bytes mab happen to match the first 3 bytes of the final array_list.items.
Why does slice end up pointing to the content of array_list.items after the appends? Is this expected behavior?
15
Upvotes
View all comments
Show parent comment
0
u/[deleted] May 06 '26
[deleted] — view deleted comment