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 comment

2

u/vip17 Sep 10 '26

a char[] has fixed size, alloca allows dynamic size. It's like std::inplace_vector in C++26 or boost small_vector and static_vector

0

u/MattDESTROYER Sep 10 '26

Not really a C++ dev, I like my C. I know the difference between a static and dynamic type lol, that wasn’t my question.

Also worth noting, I think there’s slightly more to it than your explanation, alloca let’s you create a dynamically sized buffer, but said buffer is not dynamically resizable (or freeable). Once created it’s on the stack until the end of the function call.

(So once created, alloca also has a fixed size, just like char[].)

1

u/vip17 Sep 10 '26

yes it's fixed size after allocation, just like any other malloc calls. It's not static allocation like char[] which is useful for some usecases

1

u/MattDESTROYER Sep 10 '26

You can free malloc calls and ‘resize’ them (which could simply extend or move when extending isn’t possible). alloca behaves similarly to char[] in that it can’t be freed (or resized).