I'm writing a function that needs to test some external SPI flash memory. By accident during development, I used this code
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);
...
Notice that 'len' is argument. Now the code works as expected (I tested few arguments) but my question is this correct?
I mean
uint8_t wbuff[len]
How can compiler possible know what len is @runtime to size my buffers? The commented code seems more logical (malloc).
Now the question is if code is valid, I'd prefer to not use malloc (embedded reasons). Or is just run by chance that stack is free in that region.
Thanks for clarifications (I use gnu c99).
What you have is a variable length array. Such arrays can only have automatic storage duration. In other words, they are local variables that reside on the stack in most implementations.
The definition of such arrays are defined in section 6.7.6.2 p4 of the C standard:
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.
Assuming that len
won't be big enough to overrun the stack you should be fine, otherwise you're better off with dynamic allocation.