简而言之,我坚持这些规则来决定如何分配内存块。
我在时间和空间限制加剧的嵌入式设备上工作,每当我看到 VLA 时我都会畏缩,因为我不知道底层实现会做什么以及它是否会做出正确的选择。所以我的经验法则是远离他们。是否存在使用 VLA 而不是经典 malloc 或静态分配的情况更可取,特别是在嵌入空间方面?
自动 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);
}