#When to free slices copied into ArrayList

1 messages · Page 1 of 1 (latest)

open python
#

I'm getting a memory leak with the following code:

// in function, I copy a slice into an ArrayList([]const u8)
const value_copy = try allocator.dupe(u8, value);
try innerArray.append(value_copy);

// in test, I want to free that memory:
var ret_struct = Config{
    .innerArray = std.ArrayList([]const u8).init(allocator),
};
const result = try readToStruct(&ret_struct, &parser, allocator);
defer ret_struct.innerArray.deinit();

How am I supposed to do this?

torn burrow
#

it seems like you're forgetting to free innerArray's items.
if the array-list stores inside owned slices (in your case, strings []const u8) - you'll have to free them too:

defer {
    for (innerArray.items) |item| {
        allocator.free(item);
    }
    innerArray.deinit();
}
open python
#

Ok cool, I couldn't figure out the syntax of that block