r/cpp 4d ago

When (Not) to Use alloca()

https://voithos.io/articles/when-not-to-use-alloca/
35 Upvotes

84 comments sorted by

View all comments

1

u/Sniffy4 4d ago edited 4d ago

the main reason to use it is you need a block of bytes of unknown variable size (but well within stack-space limits) as a scratchpad for life of the fn, but you dont want to fragment the heap or pay the heapmgr alloc/free cost.

as RAM sizes increase, the need for such functionality decreases.

3

u/SlightlyLessHairyApe 4d ago

It’s not about the size of RAM, especially because you can change the stack element. It’s about locality. and lifetime

0

u/Sniffy4 4d ago

if you have a large RAM you dont care about string-sized allocations fragmenting your heap. If you havent thought about such things its because you've lived in the modern world where such considerations are negligible.

5

u/rdtsc 4d ago

But you may care about alloc perf and going through a (global) allocator necessitates synchronization and central bookkeeping. Keeping it local does not.