#Dynamically allocate array on stack

1 messages ยท Page 1 of 1 (latest)

spring harbor
#

I need to allocate an array (with specified by the user size) in stack memory (I do not have dynamic allocator on my target arch yet). The size of the array will not change after allocation. Do I need to write my own allocator?

tired dew
#

The short answer to this is that you should just use a stack array + a FixedBufferAllocator.

#

Zig used to have alloca, but it was removed in favor of using a stack array with a constant upper limit as its size.

#

The stack has a limit of 1MB in total generally, which isn't a lot, so you don't really want to put any runtime quantity on it unless you really prepare for it.
Easier to just use a fixed size buffer and use that to enforce an upper limit on it

earnest bear
#

1mb? i thought it was way more

#

spawned threads, at least, have a default stack of 16 mb

tired dew
#

16MB is a LOT of stack

#

My suggestion would be to assume that you only have 1MB available, and even if you do, to not try to use it unless you're doing something really specific.

spring harbor
#

in my case I only have 64Kb of RAM on my target so not a problem ๐Ÿ˜…

tired dew
#

unless you're doing something really specific.
I'm not even sure off the top of my head what situation would even warrant that

earnest bear
#

i stack allocated a 8mb array for a ring allocator :D

tired dew
#

Also Windows defaults to a 1MB stack

#

AFAIK

#

You would not get away with that here

#

Just dynamically allocate it already ๐Ÿ˜

earnest bear
tired dew
#

What the hell lol

earnest bear
# earnest bear spawned threads, at least, have a default stack of 16 mb

it was just in another thread

/// Configuration options for hints on how to spawn threads.
pub const SpawnConfig = struct {
    // TODO compile-time call graph analysis to determine stack upper bound
    // https://github.com/ziglang/zig/issues/157

    /// Size in bytes of the Thread's stack
    stack_size: usize = 16 * 1024 * 1024,
    /// The allocator to be used to allocate memory for the to-be-spawned thread
    allocator: ?std.mem.Allocator = null,
};
tired dew
#

That is truly a ridiculous amount of stack