简体   繁体   English

分配了alloca的内存在函数结束时或范围结束时被释放?

[英]Memory allocated with alloca gets freed at end of function or at end of scope?

If I have a function like this: 如果我有这样的功能:

void bla(int size) {
    while(b){
        char tmp[size];
        ......
    }
}

tmp gets freed at each iteration of the while loop, right? tmp在while循环的每次迭代中被释放,对吗?

If I write this function: 如果我写这个函数:

void bla(int size) {
    while(b){
        char* tmp = alloca(size);
        ......
    }
}

tmp gets freed at end of scope or at end of function? tmp在范围结束时或功能结束时被释放?

It will be freed at end of function, but since you call alloca() inside the loop you'll likely get stack overflow. 它将在函数结束时释放,但由于你在循环中调用alloca() ,你可能会得到堆栈溢出。 If size doesn't change within the function you should call alloca() before the loop. 如果函数内的size没有改变,你应该在循环之前调用alloca()

alloca在堆栈上分配并且不知道作用域,所以它在离开堆栈帧后离开(=离开函数后)。

Memory allocated with alloca() is deallocated when the function exits. 当函数退出时,使用alloca()分配的内存将被释放。 See for instance the manual page for more information. 有关详细信息,请参阅手册页

Regarding the former case, of just an auto-variable in the scope, I'm not sure how you would define that it gets "freed". 关于前一种情况,只是范围内的一个自动变量,我不确定你如何定义它被“释放”。 You can't reference it outside of the scope that defines it, and if it had an initializer it would get re-initialized on each iteration. 您不能在定义它的范围之外引用它,如果它有一个初始化程序,它将在每次迭代时重新初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM