basically, what i’m doing here is allocating 1 big chunk of []u8, and then
distributing a half on ptr1 and ptr2, is this permitted?
what I need is the correct type (a pointer to a []u8) or should i try to allocate
2 buffers instead? (seems like its more easier to deallocate a single one…)
I think I would just allocate two buffers though and release both. Or use an arena if you have a lot of allocations and you want to free all of them at once.
I can’t edit anymore…what do you dont understand, I’m trying to allocate 1 buffer to two buffers, whats the type of the buffer and is it better to allocate 1 buffer or just allocate 2 buffers?
If you allocate one buffer, then you should free one buffer. Note that you also need to ‘remember’ it’s size, it’s different from C where the size is implicitly stored by the allocator interface (malloc and free).
I believe using slices instead of optional pointers to multiple elements would help you achieve this goal.
So I would rewrite it as:
I use an IDE (VSCode). I can see the types of ptr1 and ptr2 when I mouse hover them. Very handy so I highly recommend using an editor that can do this.
This sounds like a simple memory ownership labeling problem. ptr_orig is the memory owner, and ptr1 and ptr2 are references.
Zig doesn’t have a standard ownership labeling scheme. Personally, I wouldn’t put ptr1 and ptr2 in the same structure as ptr_orig with an memory ownership. Instead, I would rewrite ptr1 and ptr2 into a function to express retrieving its slice:
I will design a View for this owned struct, representing the view of the struct without ownership. Although there is no language guarantee for this semantics, it is merely my own convention.
This is completely allowable behaviour, though I would recommend that instead of using pointer arithmetic on a many pointer, you allocate a slice and make sub-slices of it instead.
This is how it might look:
ptr: [*]u8,
slice_lower: []u8,
slice_upper: []u8,
/// Allocate a single buffer of len * 2, then split it into an upper and lower buffer.
pub fn init(allocator: std.mem.Allocator, len: usize) !*obj {
const slice = try allocator.alloc(u8, len * 2);
const slice_lower = slice[0..len];
const slice_upper = slice[len..];
const ptr = slice.ptr; // All slices allow you to access their many pointer
}