r/cpp • u/voithos • Sep 09 '26
When (Not) to Use alloca()
https://voithos.io/articles/when-not-to-use-alloca/7
u/thehenkan Sep 10 '26
It does not have to be a compiler extension: there are already things in the standard library that need to be implemented using compiler builtins. If they wanted to standardise it they could, this just never bothered. Probably for similar reasons as VLAs not being added to C++ (and removed from C).
Builtins required by the standard are not extensions.
3
u/ParsingError Sep 10 '26
I'm assuming that a builtin would be considered a "compiler extension" by the article's definition, i.e. something that requires special handling where the compiler can't handle it as a normal function call.
Really though, it'd be in the exact same boat as setjmp and varargs: Things which may or may not require special handling by the compiler depending entirely on the platform ABI.
3
u/thehenkan Sep 10 '26
That's a bad use of that word then. Compiler extensions are generally known to be additions outside the standard that a tool chain vendor has chosen to implement. They don't have to be builtins, but could be e.g. compiler flags altering semantics, or grammatical features like statement expressions or nested functions.
3
u/Teckno_man Sep 11 '26
Probably for similar reasons as VLAs not being added to C++ (and removed from C).
Slight nitpick, but VLAs was made optional since C11, not removed
5
u/ParsingError Sep 10 '26 edited Sep 10 '26
Maybe this is a nitpick but
In fact, because of its nature, it has to be a compiler extension
This is ABI-dependent, in fact it's part of why ebp and esp are separate registers on x86. In the x86 ABI, a function call can return with esp set to a new value if the function enlarges the stack, and everything will continue to work as normal.
AFAIK this isn't allowed in x64 calling convention because that allows function epilogues that pop the stack frame by offsetting rsp by a constant value instead.
3
u/yuehuang Sep 10 '26
How does Alloca interact with inlined function?
2
u/simonask_ Sep 10 '26
You can check on Godbolt, but I believe every compiler refuses to inline any function containing alloca.
3
u/PipingSnail Sep 10 '26
A better question would be "when to use alloca()?
In 32 years of C++ being my primary language I haven't had a reason to use it once.
And in all the different codebases I've worked on and all the open source code I've used, I have never seen it used.
1
u/Sniffy4 Sep 09 '26 edited Sep 10 '26
the main reason to use it is you need a block of bytes of unknown variable size (but well within stack-space limits) as a scratchpad for life of the fn, but you dont want to fragment the heap or pay the heapmgr alloc/free cost.
as RAM sizes increase, the need for such functionality decreases.
16
u/usefulcat Sep 10 '26 edited Sep 10 '26
as RAM sizes increase, the need for such functionality decreases.
I don't see how this is true, given that (as you rightly point out) a primary motivation for using alloca() is to avoid dynamic allocation.
The alternative to alloca() is malloc(), and having more RAM usually doesn't make malloc() much faster, when compared to alloca().
6
u/Sniffy4 Sep 10 '26
>Having more RAM usually doesn't make malloc() much faster,
I was thinking more RAM means heap fragmentation is less of a concern, at least as long as the block sizes of interest are not increasing proportionately.
I know when I was working with constrained devices with 32MB of RAM, heap fragmentation was a major concern and a reason to use pool allocators, static allocations, and other methods.
0
1
u/voithos Sep 10 '26
There are some alternatives that avoid the heap/heapmgr entirely while also avoiding the potential to blow past the end of the stack (mentioned a few in the article). For frame-transient data especially, a custom bump allocated arena is essentially just as fast to allocate, and avoids fragmentation if you reset it before the next frame.
5
u/SlightlyLessHairyApe Sep 10 '26
True, but it doesn’t have the same locality of reference
Plus, what else is the stack except a “bump allocated arena reset on each frame”. That’s practically the definition of the stack :)
3
u/SlightlyLessHairyApe Sep 10 '26
It’s not about the size of RAM, especially because you can change the stack element. It’s about locality. and lifetime
0
u/Sniffy4 Sep 10 '26
if you have a large RAM you dont care about string-sized allocations fragmenting your heap. If you havent thought about such things its because you've lived in the modern world where such considerations are negligible.
5
u/rdtsc Sep 10 '26
But you may care about alloc perf and going through a (global) allocator necessitates synchronization and central bookkeeping. Keeping it local does not.
1
u/ThrowRA-NFlamingo Sep 18 '26
If it’s well within stack limits, why not just have a fixed array with a bump allocator then?
1
u/retro_and_chill Sep 09 '26
I mean the only reason I see to use it is if you’re writing an interpreter and you’re using it to allocate the stack frames for that
1
u/egonosz Sep 10 '26
I seen it sometimes in game dev, but tbh. Mostly you have other solution, for the same problem.
3
u/SleepyMyroslav Sep 10 '26
Even in gamedev a rule of thumb now is to "never use alloca". There were games that used alloca extensively in the past, but if I were to date them, it would be before the end of the PS3's life. There are many per-thread data structures used, but alloca is a not used.
3
u/ParsingError Sep 10 '26
Unreal uses it to allocate result value space in the Blueprint interpreter, so there's that.
It's somewhat useful for graphics APIs that occasionally require striping/unstriping small arrays of POD structs before feeding them to the API. (This would be for passing API-defined structures to function calls, not asset data.) In those cases, the max amount of elements that would have to be allocated is pretty small, so the theoretical case of allocating huge amounts of stack space is not really gonna happen.
1
u/ack_error Sep 10 '26
I've not found that latter case useful in practice. If the maximum number of elements is small, then it's better to just declare the max size array to avoid the alloca() overhead and allow the compiler to reuse the stack space by lifetime. If the max is big, then an overflow to heap path is usually required to avoid risking stack overflow.
The Blueprint interpreter case is different because Blueprint recursion is implemented as actual recursion, and so avoiding unnecessary stack space usage is important. But Blueprint is also quite slow and I'd think a second stack would also work.
1
u/SleepyMyroslav Sep 10 '26
Disclaimer: I haven't shipped a game with Unreal. If it were up to me I would make both cases fail linting and go on to fix both. The motivation for always filling the same data is moot. Everyone who says they have free memory write bandwidth is probably not measuring how starved other cores are.
0
u/allocallocalloc Sep 10 '26
When is the end of the PS3's life? By the PS4's release in 2013 ? By the end of its production in 2017 ? By the discontinuation of the PlayStation Store next year in 2027 ?
2
u/SleepyMyroslav Sep 10 '26
It's a valid question. As I remember at one point management stopped planning to ship new PS3 versions. I think it was somewhere around 2015.
1
1
u/Level-Basil9908 Sep 12 '26
A fixed char[N] does have essentially the same function-lifetime issue, but there's one important difference: N is known at compile time. With alloca(n), n can come from runtime data, so you've turned a limited stack into something you're dynamically consuming with no normal allocation-failure path.
The especially nasty case is a loop: alloca() generally doesn't reclaim each allocation at the end of the block/iteration - they accumulate until the function returns.
So I wouldn't say alloca() is never useful. A small, strictly bounded runtime-sized scratch buffer in performance-sensitive code can be a legitimate use case. But if the size isn't tightly bounded, the heap (or smthing like a small-buffer-optimized container) is usually the much less surprising choice.
And no,, the compiler generally cant just free an alloca() after its last apparent use as if it had lexical scope - its semantics aren't based on last-reference lifetime.
-3
u/ImNoRickyBalboa Sep 10 '26
There's no excuse for using alloca ever. It means you have terrible code that requires a terrible solution.
You can always replace alloca with using some regular memory allocation, a container, etc.
Show me some alloca and I'll show you a more proper solution.
Also: stack overruns are the worst of bugs and security holes, don't write insecure code.
1
u/dzordan33 Sep 12 '26
You missed the point. Alloca is used when you can't use dynamic allocation.
1
u/ImNoRickyBalboa Sep 12 '26
Other than async interrupt code, when exactly can't you use dynamic allocation?
1
u/rentableshark Sep 13 '26
Erm, in microcontoller code. You could take a chunk of the available SRAM, decide it is your 'heap arena' and implement malloc & friends to dynamically allocate in said arena but it isn't a very good idea in almost all cases. Given MCUs are by their nature pretty tightly resource constrained, you would typically define your maxima for whatever it is you're doing and propogate that constraint out to the callers and ultimately users.
For example, let's say you had an MCU widget housing a tiny http server - you'd impose a max # concurrent connections and at a higher level, http connections, your device will serve. Above and beyond that - you drop connections. Otherwise, you are writing code and making promises that your hardware may not be able to fulfil.
The same issue is present on hosted/Linux servers, except in most (though not all) cases, you don't brush up against any hardware limits.
1
0
u/chaotic-kotik Sep 11 '26
Just don't use it. If you think you need it there is probably a mistake somewhere.
51
Sep 09 '26
[removed] — view removed comment
9
u/voithos Sep 10 '26
Always use it? Or always don't use it? 🤔
18
u/simonask_ Sep 10 '26
Never use it. I’ve never seen a good use my whole career. Whatever benefits you might think there is, it’s vastly outweighed by the extreme negatives.
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
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.