用 alloca 分配的内存在函数结束时或作用域结束时被释放?结束时、函数、分配、作用

2023-09-07 03:09:15 作者:少年与梦i

如果我有这样的功能:

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

在 while 循环的每次迭代中都会释放 tmp,对吗?

tmp gets freed at each iteration of the while loop, right?

如果我写这个函数:

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

tmp 在作用域结束或函数结束时被释放?

tmp gets freed at end of scope or at end of function?

推荐答案

它会在函数结束时被释放,但是由于你在循环内调用 alloca() 你可能会得到堆栈溢出.如果 size 在函数内没有改变,你应该在循环之前调用 alloca().

It will be freed at end of function, but since you call alloca() inside the loop you'll likely get stack overflow. If size doesn't change within the function you should call alloca() before the loop.