c,函数参数的运行时缓冲区大小

c, runtime buffer size by function argument

我正在编写一个函数,需要测试一些外部 SPI 闪存。 在开发过程中偶然,我使用了这段代码

void __TO_FLASH__ slcTestCache(uint8_t len)
{
    uint16_t wcrc = 0xFFFF, rcrc = 0xFFFF;
    uint8_t wbuff[len], rbuff[len];


    //uint8_t *wbuff = os_malloc(len);
    //uint8_t *rbuff = os_malloc(len);
...

注意 'len' 是参数。 现在代码按预期工作(我测试了几个参数)但我的问题是正确的吗?

我是说

uint8_t wbuff[len]

编译器怎么可能知道 len 是多少@运行是时候调整我的缓冲区大小了? 注释的代码似乎更合乎逻辑(malloc)。

现在的问题是代码是否有效,我宁愿不使用 malloc(嵌入式原因)。或者只是 运行 碰巧那个区域的堆栈是空闲的。

感谢您的说明(我使用的是 gnu c99)。

您拥有的是一个可变长度数组。这样的数组只能有自动存储持续时间。换句话说,在大多数实现中,它们是驻留在堆栈上的局部变量。

此类数组的定义在 C standard:

的第 6.7.6.2 p4 节中定义

If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations or type names with function prototype scope; such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

假设 len 不会大到足以溢出堆栈你应该没问题,否则你最好使用动态分配。