#Do I need to deinit an empty std.ArrayList?

1 messages · Page 1 of 1 (latest)

rigid kestrel
#

Hello, I'm pretty new to Zig. In the following (approximate) code

const Tag = enum{
    variant1,
    variant2,
};

const ReturnType = union(Tag){
    variant1: void,
    variant2: std.ArrayList(u32),
};

fn someFunction(allocator: Allocator) ReturnType {
    var list = std.ArrayList(u32).init(allocator);

    for (some_iterable) |var| { 
        if (some_condition) {
            list.append(allocator, some_item);
        }
    }

    if (list.len == 0) {
        // deinit here?
        return .variant1;
    } else {
        return ReturnType{ .variant2 = list };
    }
}

i allocate a list in the body of my function, and then i may or may not, depending on the arguments of my function, add elements to it. I only return it if it has a nonzero length. Do I need to deinitialize it when I don't return it?

brittle ermine
#

If you don't add any items to the arraylist, then it doesn't have any heap allocated memory and doesn't need to free anything but to be consistent and explicit, add it anyways to tell the reader that this arraylist is definitely not used somewhere else.

#

deinit also invalidates the arraylist as a whole to catch use after free bugs.