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

10

u/MattDESTROYER Sep 09 '26 edited Sep 09 '26

Not disagreeing with anything, genuine question because I don’t know, how is alloca leaving memory allocated until the end of the function an issue, wouldn’t a char[] have the same effect?

Or do compilers optimise to drop that stack memory after the last reference in the code?

Otherwise, I see no practical difference between alloca and char[]; in which case an exact sized buffer could be a perfectly valid use case no? Assuming this is developed for a single platform too of course.

10

u/bwmat Sep 09 '26

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

3

u/MattDESTROYER Sep 09 '26 edited Sep 09 '26

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 Sep 09 '26

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 Sep 10 '26 edited Sep 10 '26

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 Sep 10 '26

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.

→ More replies (2)
→ More replies (1)

10

u/usefulcat Sep 09 '26

Not disagreeing with anything, genuine question because I don’t know, how is alloca leaving memory allocated until the end of the function an issue, wouldn’t a char[] have the same effect?

There are two problems, though neither are what you describe. The first problem is you don't know (in general) how much alloca can safely allocate. The second (and arguably much bigger) problem is that there is no error indication if it fails. And it will fail if you try to allocate too much.

When it was first invented, it was (maybe) a clever hack, though perhaps not the good kind of 'clever'. But it's absolutely a footgun and I think the number of valid use cases for it must be vanishingly small.

As the article suggests, if you want to mostly avoid dynamic allocation but still be able to support large allocations when absolutely necessary, use something like absl::InlinedVector or boost::small_vector. Worst case they may allocate but at least they won't blow up in your face. Or if you'd prefer that it blow up, at least use something obvious and intentional like assert() or throwing an exception.

3

u/splicer13 Sep 10 '26

There's no standard way to handle stack overflow*. That's not alloca specific. The problem specific to alloca is that it just empirically makes stack overflow more common. Like, if you walk through a locker room, you're going to see some dick.

InlinedVector and such are really the best option.

*also, no great way to handle it, and arguably no good way though I'd say MS SEH is pretty OK considering.

2

u/SkoomaDentist Antimodern C++, Embedded, Audio Sep 12 '26

It's slightly worse than that. On platforms with reduced stack, it's not uncommon to have only limited stack guards in place. They will detect typical stack overflows (eg. your function uses a 50 entry static array) but not something that might use many kB of stack until it's already overwritten something completely different that may trigger "impossible" behavior (like affecting another thread's stack).

1

u/MattDESTROYER Sep 10 '26

I mean, I wrote a simple PoC (for fun, I don’t intend to start using alloca lol) that seems to manage okay. Obviously everything about it is very dependent on platform/compiler specific functionality, so definitely not great or good, more on the bad, or even outright evil side lol

1

u/MattDESTROYER Sep 10 '26 edited Sep 10 '26

Yeah, gotcha, just curious lol. Now I’m curious if those problems can be solved. Is the failure case just that there isn’t enough stack memory available to the program, or are there more tricky cases (I’m assuming there’s probably more, but one can hope)?

I’m sure any way of seeing the space available on the stack would be, in general, terrible, but I may look into the possibility just for fun anyways lol

Edit: seems very possible, although the functionality may be deprecated.
https://stackoverflow.com/questions/53827/checking-available-stack-size-in-c

2

u/MattDESTROYER Sep 10 '26

To anyone that’s interested, it is, in fact, possible to make it safe(er) (that still didn’t handle the foot guns you can and likely will run into using alloca) through preventing failures due to stack overflow:
https://github.com/Matt-DESTROYER/safealloca

4

u/TheThiefMaster C++latest fanatic (and game dev) Sep 10 '26

The compiler does allow local variables to overlap addresses (or registers!) based on use not scope. So yes, if you make a char[100] the compiler will see where it's used relative to other variables in the function and potentially overlap it with them, reducing the size of the stack frame (which is generally allocated up-front at the start of the function, not bumped var by var as it would have been classically).

Alloca is much harder to do the same for, and I think most compilers don't bother.

1

u/MattDESTROYER Sep 10 '26

Ooh, this is very interesting! In what cases would it allow variables to overlap? Does the compiler essentially need to prove that only x bytes of the array are actually used and then it can chuck variables in there or something, or is that completely the wrong idea lol?

2

u/TheThiefMaster C++latest fanatic (and game dev) Sep 10 '26

If there are variables only used in the first half of the function and the array only in the 2nd, or vice-versa, it can overlap their storage.

For C++ types nontrivial constructor and destructor calls count as use that can prevent this by forcing variables to live from construction to destruction.

→ More replies (1)

1

u/MattDESTROYER Sep 10 '26

Just had a curious thought, if alloca memory always lives until the end of the function, logically if you alloca inside a closure, the memory should be accessible after the closure?

2

u/TheThiefMaster C++latest fanatic (and game dev) Sep 10 '26

Are you talking about C++ lambdas? Those don't preserve their stack at all, so no.

C++ coroutines are also stackless, and alloca breaks horribly when used in them.

→ More replies (7)

3

u/voithos Sep 10 '26

For your first question, essentially it's something like this:

void UseArray() {
for (auto& foo : foos) {
// This is a single 1024 buffer used repeatedly across the loop.
char scratchBuf[1024];
// whereas this repeatedly creates a new alloca()'d buffer for each iteration
char* scratchBuf = static_cast<char*>(alloca(n));
}
}

The array gets a fixed size, so it's always bounded, whereas alloca() does the stack allocation during each iteration without releasing anything until function return. Depending on how many loop iterations there are, and what `n` is passed to alloca(), this could be less memory than the fixed size array, or much more; the point is that it's unpredictable compared to the alternatives.

4

u/MattDESTROYER Sep 10 '26

Yeah no I understand the issue with nested scopes, but the example in the article with just a path at top level wouldn’t have that issue. I don’t know about the exact opcodes generated, but it would be generally speaking equivalent, that’s all I was clarifying.

1

u/PipingSnail Sep 10 '26

If you use alloca() in a recursive function you are massively reducing how many recursing iterations you can do before running out stack to use.

Buffer overruns on allocated memory are bad, buffer overruns on the stack are worse.

Do not use alloca(). There is just no good reason to use it. Not used it, or seen it in 32 years of c++.

→ More replies (9)

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

→ More replies (3)

2

u/cheese3660 Sep 10 '26

compilers can and i think do optimize to drop the stack memory after the last reference in the code if the reference provably does not escape the function

1

u/MattDESTROYER Sep 10 '26

Yeah, I know they can, just curious on whether they actually do; I imagine a function would have to be decently long and use a fair bit of stack memory for it to be worth it, otherwise dropping all the memory at the end of the function would likely be more efficient.

3

u/cheese3660 Sep 10 '26

Ah wait yeah not dropping, sorry, allowing that memory to be reused by other stack variables later on in the function

Because you are correct, it is easier to just once at the end of a function do something like

mov bp to sp

or

 add <frame size> to sp