gcc如何分配静态运行时间已知长度的数组(How does gcc allocate statically run time known length of array)

编程入门 行业动态 更新时间:2024-10-15 22:29:39
gcc如何分配静态运行时间已知长度的数组(How does gcc allocate statically run time known length of array)

我写了下面的代码:

int tester(int n) { int arr[n]; // ... }

此代码编译,没有警告,使用g ++。

我的问题是 - 如何? 参数n仅在运行时就已知,数组是静态分配的。 gcc如何编译这个?

I wrote the following code:

int tester(int n) { int arr[n]; // ... }

This code compiled, no warnings, using g++.

My question is - how? The parameter n is known just in runtime, in the array is statically allocated. How does gcc compile this?

最满意答案

这是GCC为C ++提供的扩展,尽管可变长度数组(“VLA”)自C99以来得到了C的正确支持。

实施不是非常困难; 在一个典型的调用堆栈实现中,该函数只需要保存堆栈帧的基础,然后按照动态指定的量推进堆栈指针。 VLA总是会提出这样的警告:如果数字太大,你会得到未定义的行为(在Stack Overflow中表现出来),这使得它们比std::vector更适合使用。

在某种程度上,我们已经努力为C ++增加一个类似的特性,但是就类型系统而言,这非常困难(例如, arr的类型是什么?它如何在函数模板中被推导出来?)。 这个问题在C语言中不太明显,它有一个简单得多的类型系统和对象模型(但是可以说,你仍然可以争辩说因为有了VLA,C会更糟糕,相当一部分标准花在了它们上面,而语言会没有他们就更简单了,而且不一定穷)。

This is an extension that GCC offers for C++, though variable-length arrays ("VLAs") are properly supported by C since C99.

The implementation isn't terribly hard; on a typical call-stack implementation, the function only needs to save the base of the stack frame and then advance the stack pointer by the dynamically specified amount. VLAs always come with the caveat that if the number is too large, you get undefined behaviour (manifesting in Stack Overflow), which makes them much tricker to use right than, say, std::vector.

There had at some point been an effort to add a similar feature to C++, but this turns out surprisingly difficult in terms of the type system (e.g. what is the type of arr? How does it get deduced in function templates?). The problems are less visible in C which has a much simpler type system and object model (but that said, you can still argue that C is worse off for having VLAs, a considerable part of the standard is spent on them, and the language would have been quite a bit simpler without them, and not necessarily poorer for it).

更多推荐

本文发布于:2023-08-01 23:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1365875.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   静态   长度   分配   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!