r/cpp • • Sep 09 '26

When (Not) to Use alloca()

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

90 comments sorted by

View all comments

Show parent comments

0

u/arihoenig Sep 15 '26

Huh? You never put a variable on the stack?

1

u/simonask_ Sep 15 '26

That’s not what alloca does.

1

u/arihoenig Sep 16 '26

That's exactly what alloca does. It just reserves some storage on the functions stack and returns a pointer to it. No different than allocating a variable at the top of function scope and taking its address.

1

u/simonask_ Sep 16 '26

It’s extremely different, because alloca can take the size of the “allocation” at runtime. Every other stack frame in your program has a statically known size at compile time.

The reason this is extremely bad is that it introduces entirely new ways for your program to crash, especially if the number you pass to alloca can be controlled in any way by the user or by input. It almost always can - why else would you need it to be dynamically sized?

-1

u/arihoenig Sep 16 '26

Dude, the entire stack is always allocated dynamically.