本文介绍了是ALLOCA彻底更换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过不少地方的的alloca 已过时,不应使用和变长数组应该使用。

I've read quite a few places that alloca is obsolete and should not be used and Variable Length Arrays should be used instead.

我的问题是:是的alloca 通过变长数组完全更换?

My question is this: Is alloca completely replaceable by variable length arrays?

在我的特定情况下我有东西,看起来像这样的:

In my particular instance I have something that looks like this:

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);
}

我缺少的东西或者这是一个实际的用好,alloca的?也因为这个例子假设由于某种原因,我想堆栈上分配值

Am I missing something or is this an actual good use of alloca? Also assume for this example that for some reason I want for the value to be allocated on the stack

推荐答案

有是VLA的和的alloca之间的一个重要区别:内存的alloca()返回的是有效的只要目前的功能仍然存在的。由VLA占用的存储器的寿命的为有效只要VLA的识别符保持在范围的。你可以的alloca()在例如循环记忆和使用的内存的之外的循环,一个VLA也就不复存在了,因为标识符超出范围时,循环终止。这意味着,你可以由alloca()和足够的堆栈空间做到这一点:

There is an important difference between VLA's and alloca: The memory alloca() returns is valid as long as the current function persists. The lifetime of the memory occupied by a VLA is valid as long as the VLA's identifier remains in scope. You can alloca() memory in a loop for example and use the memory outside the loop, a VLA would be gone because the identifier goes out of scope when the loop terminates. This means, you can do this with alloca() and enough stack space:

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..

您不能沃拉斯做到这一点。

You can't do this with VLAs.

这篇关于是ALLOCA彻底更换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 13:47