我读过很多地方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);
}
我是否遗漏了一些东西,或者这是 alloca 的实际用途吗?还假设在此示例中,出于某种原因,我希望在堆栈上分配该值
VLA 和 alloca 之间有一个重要区别:alloca() 返回的内存是有效的只要当前功能仍然存在。 VLA占用的内存的生命周期为只要 VLA 的标识符仍在范围内就有效。例如,您可以在循环中分配内存并使用内存outside在循环中,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..
您无法使用 VLA 执行此操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)