arduinoavrarduino-c++avr-gccstatic-memory-allocation

Is there a way to create a static array in the .data section, where its length is calculated by the size of the .bss section on the Arduino?


I'm just wondering if there is a way I can tell the compiler that I want to create a static array inside the .data section of the Arduino's SRAM, where the array's size is calculated using the size of the .bss section.

enter image description here

It should technically be possible since the .bss is calculated at compile time.


Solution

  • There is no way to do this in a standard compliant way since the C/C++ standard(s) know nothing about .bss or .data or their lengths.

    One way is to allocate a respective data buffer on the heap (use malloc) or on the stack (use alloca). The overhead of alloca is less than that of malloc, but alloca'ted memory has only the lifetime of a similar auto variable.


    Closest to the requested feature is to "allocate" an array buf[] after .bss like so:

    extern char buf[] __asm("__heap_start");
    extern char __bss_start[];
    extern char __bss_end[];
    
    int main (void)
    {
      const size_t buf_size = __bss_end - __bss_start;
      memset (buf, 0, buf_size); // Clear buf[]
      buf[0] = 'A';              // Access buf[]
      ...
    

    This is not compatible with malloc, which starts allocation at __heap_start. You can cater for that with:

      extern char *__malloc_heap_start;
      __malloc_heap_start += buf_size;
    

    prior to the first call to malloc et al. (alloca is no issue).