gpt4 book ai didi

c - 在嵌入式系统中使用 c 中的可变长度数组是否存在问题?

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:02 25 4
gpt4 key购买 nike

有人告诉我用非常量值初始化数组是错误的,但我需要知道为什么。

int length = 5 ; 
int array[length];

最佳答案

根据 Linus Torvalds 的说法,可变长度数组没有给嵌入式编程世界带来任何积极值(value),并且带来了问题包袱,包括稳定性和速度问题。建议在合理的情况下只使用足够大的固定大小的数组,或者在不合理的情况下在堆上分配数组。

VLA's are problematic for embedded and systems programming because the stack is usually very limited. Code generation is also generally negatively affected, which can make it a very inconvenient feature (frame pointers aren't free, and registers can often be used more effectively for other things).

If your array length is limited to a known value, you're often better off just using the maximum size. And if the maximum size is too large for that to be a good approach, see above about limited stack sizes.

In short: VLA's don't buy you anything in embedded and systems programming, and they do cause problems.

[...]

Some people really don't seem to realize that embedded and system programming is different from "normal" programming. Resources are limited and you must not just fail. You generally cannot just say "oops, I don't have enough memory, I'll just exit".

https://www.realworldtech.com/forum/?threadid=121531&curpostid=121621

Linus 的进一步意见,摘自 Linux 内核邮件列表:

AND USING VLA'S IS ACTIVELY STUPID! It generates much more code, and much _slower_ code (and more fragile code), than just using a fixed key size would have done.

https://lkml.org/lkml/2018/3/7/621

我还认为值得重申 Eric PostPischil 的评论,即从 C11 开始,VLA 是可选的。在嵌入式系统中工作时,您会看到更多种类的硬件架构,其中一些可能更难实现 VLA,因此您遇到不支持它们的系统的可能性并不小。

从我读到的有关此事的内容来看,似乎 VLA 通常是使用帧指针实现的,但并非所有架构都有帧指针。

关于c - 在嵌入式系统中使用 c 中的可变长度数组是否存在问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57009281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com