Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can not alloca be used in function argument list?

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 by alloca() 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 ints) 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?

like image 769
Naitree Avatar asked Mar 10 '23 00:03

Naitree


1 Answers

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):

  1. Pushes 2 into the activation record stack space.
  2. Performs alloca(100), which sucks down the same stack holding the call activation record being built by an additional 100 char.
  3. Pushes the result of (2), a void*, into the activation record stack space.
  4. Pushes 1 into the activation record stack space.
  5. Invokes 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.

like image 119
WhozCraig Avatar answered Apr 29 '23 20:04

WhozCraig