Hey everyone, I am a new zig user coming to learn the language for embedded development. I used this year's advent of code to get myself started, and I have a question about the right way to free memory with defer:
// let's say i have an array of arraylists and i want to both initialize them
// in a loop while also making sure the memory is cleared when it's no longer
// needed
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var stack_array: [9]std.ArrayList(u8) = undefined;
var index: usize = 0;
while (index <= 8) : (index += 1) {
stack_array[index] = std.ArrayList(u8).init(gpa.allocator());
defer stack_array[index].deinit(); //<- doesn't this clear memory
} //<- here?
After we have left the scope of the while, I can do things with my array of arraylists "stack_array" even though the deinit() should have happened at the end of the while. I am not sure why this is. Perhaps is it because stack_array was declared outside of the while? Where would the right place to put deinit() be in this case?