#Help understanding ArrayList.toOwnedSlice

1 messages · Page 1 of 1 (latest)

pastel gorge
#

I have a function call where i create an ArrayList(u8) but I don't defer list.deinit() because I want to return an owned ArrayList to the caller function. The reason, acc. to my understanding is if I do return a slice i.e. []const u8 and call defer list.deinit() then my slice will point to invalid or freed memory which is rarely what anyone wants.

So searching around I found toOwnedSlice which seems like it does what I want that is return an []u8 but it clears or empties the arraylist? I don't understand this comment, does calling this method free the array list? If so then what is the returned slice a view of?

reef blaze
#

toOwnedSlice "moves" the memory out of the arraylist, such that a deinit() on the list no longer does anything to the toOwnedSlice result

#

to get a "view" while still having the arraylist own the allocation, use array_list.items

pastel gorge
#

I understand that the memory of the arraylist no longer holds the backing data, but the slice returned, what does it point to? Some arbitrary memory address outside the array list?

silent lagoon
pastel gorge
#

Ah I see. So in the case where we don't turn the ArrayList into an owned slice, the arraylist itself is responsible for calling free on the slice

the free syntax changes from list.deinit() to allocator.free(owned_slice)

#

Would this code sample be considered correct?


    try file_name.appendSlice(suffix);

    const result = try file_name.toOwnedSlice();
    defer allocator.free(result);

    return std.fs.path.join(allocator, &.{ base_dir, result });
#

since I am creating a separate path allocation

silent lagoon