linuxmallocalloca

calling alloca( ) from another function call parameter?


Why calling alloc( ) as a parameter to another function call like this func(x, alloca(size), z); is considered wrong According to a book called the linux programming interface

This is because the stack space allocated by alloca() would appear in the middle of the space for the function arguments (which are placed at fixed locations within the stack frame). Instead, we must use code such as this:

  void *y; 
  y = alloca(size); 
  func(x, y, z); 

while This is wrong

func(x, alloca(size), z);  /* WRONG! */

isn't those 2 pieces are supposed to be equivelent .In the first one alloca is called first then func is called with it's return value, so if someone can explain how alloca allocate memory on stack that make both approaches different.


Solution

  • The alloca man page mentions this in the BUGS section:

    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.

    E.g. in func(x, alloca(1000), z); you might end with a stack layout like

     sp+100c:    x
     sp+1008:    .... space reserved by alloca
     sp+   8:
     sp+   4:    sp+8 (return value of alloca())
     sp+   0:    z
    

    Common ABIs require that parameters of func(void *, void *, void *) are at the locations [sp + 0], [sp + 4] and [sp + 8]. There is expected a layout similarly to

     sp+100c:    .... end of space reserved by alloca
     sp+   c:    .... space reserved by alloca
     sp+   8:    x
     sp+   4:    sp+0x0c (return value of alloc())
     sp+   0:    z