是否需要从堆栈中分配C可变长度数组? [英] Is it required that a C Variable Length Array is allocated from the stack?

查看:118
本文介绍了是否需要从堆栈中分配C可变长度数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从嵌入式系统的代码中删除了对malloc和calloc的所有调用之后,我很惊讶地发现malloc仍在链接.调用图将我指向一个没有显式* alloc调用的函数,并且没有调用任何可能分配的库函数,例如strdup.
我必须查看生成的程序集,以意识到这是由于包含VLA的内联函数引起的.

After removing all the calls to malloc and calloc from our code for an embedded system, I was surprised to find that malloc was still being linked in. The call graph pointed me to a function which had no explicit *alloc calls, and no calls to any library functions that might allocate, like strdup.
I had to look at the generated assembly to realize that it was due to an inlined function which contained a VLA.

我认为VLA必须进行堆栈分配.这个编译器坏了吗?

I thought VLAs had to be stack-allocated. Is this compiler broken?

推荐答案

没有要求从堆栈中分配VLA(语言标准甚至没有提到堆栈或堆).唯一的要求如下:

There is no requirement that VLAs be allocated from the stack (the language standard doesn't even mention stacks or heaps). The only requirement is as follows:

6.2.4对象的存储期限
...
7对于确实具有可变长度数组类型的对象,其生存期从 对象的声明,直到程序执行离开范围 声明. 35)如果以递归方式输入范围,则将创建该对象的新实例 每一次.对象的初始值不确定.
35)离开包含声明的最里面的块,或跳转到该块中的某个点或 声明之前的嵌入式块会离开声明的范围.
6.2.4 Storage durations of objects
...
7 For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration.35) If the scope is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate.
35) Leaving the innermost block containing the declaration, or jumping to a point in that block or an embedded block prior to the declaration, leaves the scope of the declaration.

鉴于此,从堆栈中进行分配是有意义的,但对于非常大的对象而言,这可能是不可能的,而是可以从堆或其他内存段中分配此类对象.簿记取决于实施情况.

Given this, it makes sense to allocate from the stack, but for very large objects this may not be possible, and such an object may be allocated from the heap or some other memory segment instead. The bookkeeping is up to the implementation.

这篇关于是否需要从堆栈中分配C可变长度数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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