从另一个函数调用参数调用 alloca()?

calling alloca( ) from another function call parameter?

为什么像这样调用 alloc( ) 作为另一个函数调用的参数 func(x, alloca(size), z); 被认为是错误的根据一本名为 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); 

虽然这是错误的

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

是不是那 2 件应该是等价的。在第一个 alloca 被调用然后 func 用它的 return 值被调用,所以如果有人可以解释 alloca 如何在堆栈上分配内存使两种方法不同。

alloca 手册页在 BUGS 部分提到了这一点:

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.

例如在 func(x, alloca(1000), z); 中,您可能会以

这样的堆栈布局结束
 sp+100c:    x
 sp+1008:    .... space reserved by alloca
 sp+   8:
 sp+   4:    sp+8 (return value of alloca())
 sp+   0:    z

普通 ABI 要求 func(void *, void *, void *) 的参数位于 [sp + 0][sp + 4][sp + 8] 位置。预计布局类似于

 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