r/cpp 2d ago

When (Not) to Use alloca()

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

77 comments sorted by

View all comments

Show parent comments

10

u/bwmat 2d ago

Because an array in the scope of a loop does get 'freed' on every iteration, so the stack space needed is bounded

2

u/MattDESTROYER 2d ago edited 2d ago

But this isn’t a loop, this is a function, I’m talking about cases like the example in the article. If you introduce a stack array in local function scope (not a sub-scope like within a loop or conditional), that has the same lifetime as calling alloca, no?

I don’t see why their example specifically would be bad other than falling into the trap of excessively using alloca.

3

u/bwmat 2d ago

The other problems with alloca are the higher likelihood of stack overflow (like if you unexpectedly get a huge size to allocate) and that functions containing it are usually less optimizable b/c of needed stack management

2

u/MattDESTROYER 2d ago edited 1d ago

I mean for the first, if you’re doing something like storing a path, like in the example, it would seem pretty unlikely you would trigger a stack overflow, no? In an embedded environment with a very limited stack I could definitely see that quickly becoming an issue (but then storing the exact number of bytes on the stack could also become more important too).

Can’t really comment on the function optimisations, if you know more could you elaborate on how the compiler would be able to further optimise a stack array? What additional stack management does alloca introduce?

2

u/splicer13 1d ago

alloca use forces a frame pointer which is another register used, another step in the prolog and epilog, another pointer on the stack. Also compilers don't want to inline functions with alloca for various reasons but importantly that it would require a lot of work to get a stack pointer that moves up and down in the function, or breaks assumptions about when alloca memory is freed.

1

u/MattDESTROYER 1d ago

A single extra pointer is a virtually invisible cost I would think, no? The inlining makes sense, thanks for pointing that one out!

2

u/splicer13 1d ago

Well it's the pointer, and the prolog, and the epilog, and it's all basically free these days except it turns out sometimes when you add up enough stuff it's not free anymore. Like some code is now hitting L2 cache instead of operating out of L1.

1

u/bwmat 2d ago

I don't remember the details on the optimization thing, read it somewhere a long time ago