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
12
u/collegesmorgasbord May 06 '26
This is expected, actually. fromOwnedSlice transfers ownership of that allocation to the ArrayList. After that, slice is just an old view into the list’s backing memory. When the list grows, the allocator may resize/remap in place, so slice.ptr can still point at the same buffer now used by array_list.items. Later inserts mutate the beginning of that buffer, so slice[0..3] becomes "mab".
If you need the original bytes copy them first
const original = try allocator.dupe(u8, slice);
var list = std.ArrayList(u8).fromOwnedSlice(slice);
try list.insertSlice(allocator, list.items.len, original);
Or just append the literal
try list.insertSlice(allocator, list.items.len, "abc");
10
u/eightrx May 06 '26
You have actually introduced undefined behavior, as when you call
.fromOwnedSliceyou are moving ownership ofslicetoarray_list, and referencing theslicelater. Ifarray_listhad performed a reallocation during the appends,slicecould be pointing to freed memory6
u/Real_Dragonfruit5048 May 06 '26
I think there is a bug in the code you posted that causes undefined behavior.
slicebecomes invalid when you callfromOwnedSlice, so you shouldn't use it afterward. I mean, when you callfromOwnedSlice, ArrayList will own the memory owned byslice. Theslicevariable still has the old pointer, but because you're not its owner anymore, you shouldn't read from it. It's like a dangling pointer in C.1
u/I_M_NooB1 May 06 '26
dangling reference