Force runtime array allocation and initialization with list syntax-Collection of common programming errors
I am working on an atmega328 that only has 2K of RAM.
I use a script to create 10bytes arrays from 10 bitmaps that represent 10 digits of my LCD timer. Those byte arrays are stored in my source code but since I only write one digit at time there is no reason to keep all of them in RAM. This way I can use bigger digits and consume less RAM!
This is what I am trying to do:
void load_digit_ba(uint8_t digit, uint8_t digit_ba[]) {
// from 0 to 9 I copy the current digit in the byte array form into digit_ba
if (digit == 0) {
uint8_t digit_ba_tmp[10] = { 24, 40, 0, 0, 0, 224, 240, 248, 252, 254 };
memcpy(digit_ba, digit_ba_tmp, 10);
}
...
}
But it seems that the compiler is statically reserving memory for all the arrays. In my case 122 bytes * 10 digits = ~1K, more than half of my RAM.
Sketch uses 7,310 bytes (23%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,695 bytes (82%) of dynamic memory, leaving 353 bytes for local variables. Maximum is 2,048 bytes
If I add a cell to the array [11] instead of [10] and just pass 10 value as initializers it will instead allocate the memory at runtime (it seems):
void load_digit_ba(uint8_t digit, uint8_t digit_ba[]) {
if (digit == 0) {
uint8_t digit_ba_tmp[11] = { 24, 40, 0, 0, 0, 224, 240, 248, 252, 254 };
memcpy(digit_ba, digit_ba_tmp, 10);
}
...
}
Aurdino IDE says:
Sketch uses 11,396 bytes (37%) of program storage space. Maximum is 30,720 bytes.
Global variables use 597 bytes (29%) of dynamic memory, leaving 1,451 bytes for local variables. Maximum is 2,048 bytes.
Same behavior if I do uint8_t digit_ba_tmp[]
letting the compiler figure the length, it reserves ~1K RAM.
Why adding a cell does that and is it clean? Doesn’t seem to me. The assumption here is that since the length of the digit array is fixed for every digit, just changes the content, and I send one digit at time over serial to the display, it makes sense to just load the current digit into ram and then send it. I don’t see any heap/stack memory fragmentation issue here, am I right? smiley-sad