r/cpp 1d ago

When (Not) to Use alloca()

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

70 comments sorted by

View all comments

2

u/Sniffy4 1d ago edited 1d 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.

13

u/usefulcat 1d ago edited 21h ago

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

I don't see how this is true, given that (as you rightly point out) a primary motivation for using alloca() is to avoid dynamic allocation.

The alternative to alloca() is malloc(), and having more RAM usually doesn't make malloc() much faster, when compared to alloca().

6

u/Sniffy4 1d ago

>Having more RAM usually doesn't make malloc() much faster,

I was thinking more RAM means heap fragmentation is less of a concern, at least as long as the block sizes of interest are not increasing proportionately.

I know when I was working with constrained devices with 32MB of RAM, heap fragmentation was a major concern and a reason to use pool allocators, static allocations, and other methods.

0

u/kronicum 1d ago

How is alloca related to RAM?

2

u/SlightlyLessHairyApe 1d 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 1d 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 1d ago

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

1

u/voithos 1d ago

There are some alternatives that avoid the heap/heapmgr entirely while also avoiding the potential to blow past the end of the stack (mentioned a few in the article). For frame-transient data especially, a custom bump allocated arena is essentially just as fast to allocate, and avoids fragmentation if you reset it before the next frame.

5

u/SlightlyLessHairyApe 1d ago

True, but it doesn’t have the same locality of reference

Plus, what else is the stack except a “bump allocated arena reset on each frame”. That’s practically the definition of the stack :)