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.
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.
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.
Definitely don’t intend to use it lol, I just like messing around with with things when I learn about them.
For the first, curious how it reduces how many recursive iterations you can do, because using char[] will also equally consume the stack in a recursive function, no?
Alloca uses space on the stack. Therefore it reduces the amount of remaining stack for future recursive calls which will also use alloca() which uses stack space which reduces space for future calls...
Can you see the problem?
If you had no local cars and no alloca() you could do total remain stack space / size if machine word recursive calls befire stack overflow.
On a Windows machine default stack size is 1MB. X86 machine size is 4 bytes. X64 machine size is 8 bytes.
For this example let's assume after programme startup you have 1,000,000 byes of stack space. It makes the maths easier.
So the max num recursion is appriox 250,000 for x86 and approx 125,000 on x64.
Let's say your alloca() call uses 8 bytes.
Now on x86 each call uses 4 + 8 bytes, 12 bytes.
1,000,000 / 12 = 83,333 recursion before stack overflow.
On x64 each call now takes 8 + 8 bytes, 26 bytes.
This leaves space for 1,000,000 / 16 = 62, 500 recursions before stack overflow.
I think you’re making an unfair comparison; unless I’m misunderstanding, you’re compare `alloca` to doing nothing, which isn’t realistic.
What would be realistic is using a static char[] array, but this still consumes memory in every recursive call. The difference would be a single pointer variable and also the lack of ability to not store the frame pointer in a register.
If you're doing anything recursive you try to use as little stack space as possible.
Therefore you wouldn't use a local variable char array, or alloca(). You'd dynamically allocate your workspace, or pre allocate enough space prior to the recursive call.
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.
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
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?
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.
Well it's the pointer, and the prolog, and the epilog, and it's all basically free these days except it turns out sometimes when you add up enough stuff it's not free anymore. Like some code is now hitting L2 cache instead of operating out of L1.
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.
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.
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).
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
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
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
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.
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?
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.
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?
No, not a C++ person lol, I’m talking about something like something like this: ```c char* x; { char* y = alloca(1); y[0] = ‘a’; x = y; } printf(“%c\n”, *c); ``` Reading a stack allocated value outside of the closure it was created in. I mean if you think of it like malloc, it makes perfect sense that it would work, but the fact that it’s a stack allocated value makes it seem strange and evil to me lol (and I mean it’s obviously not something you should ever do, but it’s interesting that it’s possible, reminds me of `var` in JavaScript minus the hoisting).
Basically they're a function inside another that captures some state from its enclosing parent and saves it for later. C++ lambda functions are an example.
They're an old concept, and people sometimes try to implement them (badly) in C.
Yeah I searched it up, I’ve used lambdas in other languages like Python and JS. Would it be accurate to say the act within the scope they were defined, meaning they can use variables defined in the scope they are defined in theory?
Yes they can use those variables - but the memory returned by alloca isn't a variable itself, and wouldn't be captured by a closure - only the pointers to it (which would point to stale stack memory as soon as the parent function returned even though the closure still existed).
This is what I was talking about with alloca not working with C++ lambdas (which are a form of closure).
This is what I thought you were asking about when you said "closure" initially.
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[].)
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).
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
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.
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.
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.
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.
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.
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.
>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.
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.
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.
But you may care about alloc perf and going through a (global) allocator necessitates synchronization and central bookkeeping. Keeping it local does not.
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.
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.
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.
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.
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 ?
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.
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.
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.
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?
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.
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.
5
u/ParsingError Sep 10 '26 edited Sep 10 '26
Maybe this is a nitpick but
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?
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.
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/Life_Sink9598 Sep 10 '26
In Hotspot we use a thread-local arena for scratch allocations.
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.
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
u/[deleted] Sep 09 '26
[removed] — view removed comment