什么时候使用可变长度数组(VLA)?

问题描述 投票:0回答:1
  • malloc 很慢并且在堆上分配。适用于大型物体或 需要将生命周期延长到函数之外的对象 它们是在哪里创建的。
  • 静态分配在栈上。由编译器烘焙的分配 所以基本上是免费的。适合小物件。风险 否则。

简而言之,我坚持这些规则来决定如何分配内存块。

我在时间和空间限制加剧的嵌入式设备上工作,每当我看到 VLA 时我都会畏缩,因为我不知道底层实现会做什么以及它是否会做出正确的选择。所以我的经验法则是远离他们。是否存在使用 VLA 而不是经典 malloc 或静态分配的情况更可取,特别是在嵌入空间方面?

c memory allocation variable-length-array
1个回答
0
投票

自动 VLA 通常不是很有用,但 VM 类型有一些用途:

  • 将数组传递给函数时检查大小
#include <stdio.h>

void f(const size_t size, const int buf[static size]);

int main(void)
{
    int arr[50] = { 0 };
    f(10, arr);  // acceptable
    f(50, arr);  // correct
    f(100, arr); // *WARNING*
    return 0;
}
  • 一次
    malloc()
    调用分配多维数组
// `n` and `m` are variables with dimensions
int (*arr)[n][m] = malloc(sizeof *arr);
if (arr) {
    // (*arr)[i][j] = ...;
    free(arr);
}
© www.soinside.com 2019 - 2024. All rights reserved.