for ([_]u16{
512,
1024,
2048,
4096,
8192,
16384,
32768,
}) |blockSize| {
var buf = allocator.alloc(u8, blockSize);
}```can I avoid having to use an allocator for this?
#avoid allocator
1 messages · Page 1 of 1 (latest)
What are you trying to do
yeah there's not much context here :(
I'm trying to obtain the blockSize of a block device by bruteforcing. I need to make a buf but would prefer not to have to use the heap.
create a buffer array of max size
32768 in this case
then slice it from 0..block_size
and done!
no allocations needed :)
Wouldn't this only work based on a page allocator
you can try std.BoundedArray, max len at comptime, but it acts like an ArrayList in the way that if its not filled up all the way you have a normal length value
very cute array
Also, pardon my ignorance as I'm not experienced in memory management, if I create a buffer, will that memory be used throughout the entire runtime of the program? So if I do make an array of 32768, will that 32K be used even once the function is done?
unless it's static memory, it's on the stack
and, is that good practice?
which means it's gone after the scope
for ([_]u16{
512,
1024,
2048,
4096,
8192,
16384,
32768,
}) |block_size| {
var buf: [32768]u8 = undefined;
var block = buf[0..block_size];
}
is the code for my solution btw
Would it be better if the buf was established outside the for loop?
Should be the same
doesn't change anything but sure
for clarification, the 32k would last the duration of the program if it was on the global scope (static i think)
but otherwise, it 'dies' at the end of its scope
I am really not knowledgeable in terms of memory so these are very base level, but would this super buf of sorts be better practice than using an allocator? Should I use this if I know the max size? Is an allocator only really for if it is completely unknown?
yep, pretty much
here the max size is known and it's reasonably small, so you can use a buffer
allocators have to perform an allocation syscall at some point which makes them "slower"
if you know an upper bound and it cam reasonably fit in the stack its gud to use a buffer
the slowness depends on how many times that syscall is made
oh im just parroting what auguste is saying sry
Thanks for this, I now have a SUPER_BUF
yey
and if you want to have length dsta stored in it even if its not fully filled, you can use BoundedArray
it compiles to a regular array pretty sure
a boundedarray is just an array like this with an index element :)