alloca完全可以替换吗?

Ear*_*rlz 8 c arrays alloca

我已经阅读了很多alloca过时的地方,不应该使用,而应该使用可变长度数组.

我的问题是:alloca可变长度数组是否完全可以替换?

在我的特定实例中,我有一些看起来像这样的东西:

typedef struct { 
  int *value; 
  size_t size; 
  } some_type;

void SomeExternalFunction(some_type);

...

void foo(){
  //What I thought to do
  some_type bar;
  bar.value=alloca(sizeof(int)*10);
  SomeExternalFunction(bar);

  //what should be done without alloca
  some_type fizz;
  int tmp[10];
  fizz.value=tmp;
  SoemExternalFunction(fizz);
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么或者这是对alloca的实际使用吗?另外假设这个例子由于某种原因我想要在堆栈上分配值

Nor*_*ame 22

VLA和alloca之间存在重要区别:只要当前函数持续存在,内存alloca()返回就是有效的.只要VLA的标识符保留在范围内,VLA占用的内存的生存期就是有效的.例如,你可以在一个循环中分配()内存并使用循环外部的内存,因为当循环终止时标识符超出范围,VLA就会消失.这意味着,您可以使用alloca()和足够的堆栈空间来执行此操作:

typedef struct node { int data; struct node *next; };
void fun()
{
 struct node *n=0;
 int d;
 /* Now we are building a single-linked list on the stack! */
 while(d=get_something()) {
  struct node *x=alloca(sizeof(*x));
  x->next=n; 
  x->data=d;
  n=x;
 }
 do_something_with(n);
} // and the whole thing is deleted here..
Run Code Online (Sandbox Code Playgroud)

你不能用VLA做到这一点.