Deallocating a sub-slice

I am fairly new to Zig and I love it :smiling_face_with_three_hearts:
Let’s say I read a file to an allocated buffer. Then I want to pass a large portion of that buffer in a struct with few other values concluded from reading a file, like decoding an image or readin a mesh. So I need that buffer for some time and then I want to deallocate it but I only passed a subslice[N…] of that original file_content buffer/slice. I see Zig does allow me to deallocate that subslice but does it also deallocates tat original file_content allocation? If not how to properly do it? Should I make a second slice and copy the content or pass the file_content reference for later deallocation? I am using 0.14.0-dev.1576+5d7fa5513

1 Like

Generally the allocator interface is built on the promise that you always free the same pointer+length that you allocated. This allows more efficient allocator implementations than for example in C/C++ because the allocator doesn’t need to do any bookkeeping.

So unless you got a special allocator, where you know it won’t matter (like an ArenaAllocator, which doesn’t actually free the memory when calling free anyways), what you are doing is undefined behavior.

So either you need to keep track of the original slice somewhere, or like you said you could make a copy. (Or you could also consider using an ArenaAllocator, which you deinit at the end instead of freeing the slice)

Also I’d recommend to use a GeneralPurposeAllocator for testing, since it has runtime safety checks for cases like this.

3 Likes

If the lifetime of the original buffer is only needed to find the sub slice, I think std.mem.Allocator.dupe() is your friend here. Basically, you could do:

const original_buf = try getYourAllocatedBuffer();
// Do whatever processing you need to find the sub slice bounds. Represented below as `start` and `end`.
const sub_slice = try alloc.dupe(u8, original_buf[start..end]);
alloc.free(original_buf);
// Continue to use `sub_slice` as needed.
3 Likes

A sub-slice is just a view into something else. It is not allocated itself, so should never be deallocated. The data has the lifetime of the parent slice’s lifetime.

5 Likes

Thanks for your help folks. I cannot select “Solution” for more then one post it seems but all of you gave me some other useful insight into the problem. Thanks a lot!

2 Likes