I have hooked up external SRAM memory in my project. What I want to do is to use malloc() to store data in external OR internal memory in runtime. How can I decide during code execution in which memory store heap data with malloc? I know I have to edit linker script but after that it will store ALL heap data in external memory. Is there any linker command that can say to allocate next malloc() in external or internal memory? For stack data we can use attribute((section("name"))) variable attribute but is there anything for heap?
Thank you!
malloc
from your C library can generally only use memory from one location. If you use newlib then it finds this memory using _sbrk
. The default implementation of _sbrk
depends on the definition of the symbol end
or _end
by the linker script, but you can also implement your own.
You will have to pick one location for malloc
to access, and use your own custom function to allocate memory from somewhere else.
Many libraries and RTOS implementations do this. See for example mem_malloc
in LwIP or rt_alloc_mem
in Keil RTX
There are many schemes you can use to decide which memory to use, for example having pools of fixed size blocks for a particular purpose. I tend to use the fastest internal SRAM for malloc
because it will become quite fragmented. I then make sure to only use malloc
for small things and then custom functions for larger allocations.