Any downsides to allocate array on Heap instead of Stack?

DSP, Plugin and Host development discussion.
RELATED
PRODUCTS

Post

>If 'f' function has data-dependent stack size, it's already unsafe to begin with.

You are correct that they are unsafe, but data-dependent stack size is true for nearly all functions you write/encounter. E.g. in `f(x) {if (x == 1) g()}`, the callstack size of `f` is increased based on the function's data.

Overall, what I'm saying is that there are reasons to use alloca()/VLAs over fixed-sized arrays. If it makes you feel better, use `assert(len <= MAX_LEN)` before calling alloca(), so then there are *no* disadvantages of using variable stack allocation. But IMO there is no way to make a perfect judgement of MAX_LEN, so I prefer to omit the assertion and suggest a rough stack size estimate in the documentation.
VCV Rack, the Eurorack simulator

Post

Nobody mentioned here that could just have a big heap block pre-allocated, and a stack like allocator on that block.
no need to free memory, you just "reallocate" on the next frame
Hence you get the better of the two worlds, ultra fast allocation, and not messing with the stack.

Post

vortico wrote: Sun Jun 16, 2019 2:43 pm >If 'f' function has data-dependent stack size, it's already unsafe to begin with.

You are correct that they are unsafe, but data-dependent stack size is true for nearly all functions you write/encounter. E.g. in `f(x) {if (x == 1) g()}`, the callstack size of `f` is increased based on the function's data.
You can still reasonably estimate the worst case if your call tree is not deep. Recursion can happen e.g. in an FFT algorithm, but most likely you want a heap memory for it.
vortico wrote: Sun Jun 16, 2019 2:43 pm Overall, what I'm saying is that there are reasons to use alloca()/VLAs over fixed-sized arrays. If it makes you feel better, use `assert(len <= MAX_LEN)` before calling alloca(), so then there are *no* disadvantages of using variable stack allocation. But IMO there is no way to make a perfect judgement of MAX_LEN, so I prefer to omit the assertion and suggest a rough stack size estimate in the documentation.
And what are the advantages of alloca compared to preallocated memory? Yeah, maybe a few Kbytes of a hot memory, and ONLY if it's actively used and freed by the host (other plugins?) or your code. If it's your code, you can reuse the heap memory yourself (though it's not convenient), and if it's not your code, nothing can be done about it.

Post Reply

Return to “DSP and Plugin Development”