使用 alloca 分配的内存在函数结束时还是在作用域结束时被释放? [英] Memory allocated with alloca gets freed at end of function or at end of scope?

查看:54
本文介绍了使用 alloca 分配的内存在函数结束时还是在作用域结束时被释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的功能:

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

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

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.

这篇关于使用 alloca 分配的内存在函数结束时还是在作用域结束时被释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆