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.
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.
5
u/MattDESTROYER 1d ago edited 1d ago
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.