Quoting the second paragraph of BUGS
section, from manpage of alloca(3)
On many systems
alloca()
cannot be used inside the list of arguments of a function call, because the stack space reserved byalloca()
would appear on the stack in the middle of the space for the function arguments.
I failed to see how this would happen. Taking the following code as example:
void f(int a, void * b, int c);
int
main(void)
{
f(1, alloca(100), 2);
}
Based on my understanding, alloca
expands the stack frame for main
down 100 bytes (by modifying stack pointer register), then the pointer to that block of stack memory (along with 2 int
s) is passed on stack frame for f
. So the allocated space shouldn't be in the middle of a
, b
or c
, actually it should be on a different frame (which is on frame for main
in this case).
So what's the misunderstanding here?
First, note right away that alloca
is not standard. It is an extension to platforms that wanted to give even more ways for programmers to hang themselves by potentially dynamically consuming automatic variable space in the interest of speed over slow dynamic memory allocators based on other techniques (heaps, etc). (yes, my opinion, but there's much truth within).
That said, consider this:
Have you ever written a compiler before? There is no standard guarantee of evaluation order of function arguments. So just suppose some platform chose to build the activation record for a call to f
by ultimately pushing the following into the activation stack, from right to left (their choice):
alloca(100)
, which sucks down the same stack holding the call activation record being built by an additional 100 char
.void*
, into the activation record stack space.call f
which, pushes the return address in main
into the activation record stack space.Now, think of yourself as the function f
. Where do you expect to find the third parameter to your function? Um....
That is just one example of how one can toss alloca
space somewhere that can cause problems.