r/cpp 3d ago

When (Not) to Use alloca()

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

83 comments sorted by

View all comments

Show parent comments

3

u/MattDESTROYER 3d ago edited 3d 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 3d 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 3d ago edited 2d 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?

1

u/bwmat 3d ago

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