I need to use a library in my Zoul project which uses extensively the malloc mechanism to allocate dynamic memory.
The problem is when this library calls malloc it returns NULL since the there is not enough memory in the heap.
I have tried this simple function to see how much memory i have at the start of the program:
size_t heap_size(){
uint8_t* p = NULL;
size_t size = 0;
while((p = malloc(sizeof(uint8_t))) != NULL)
size++;
return size;
}
Which gives me a heap of just 92 bytes.
In the output of the device i can see it has an SRAM of 32 KiB. Is there a way to enlarge the portion dedicated to the heap?
There is no such way. If you look at the linker script of Zoul's CPU (CC2538), you can see these definitions that are relevant:
.bss :
{
_bss = .;
*(.bss*)
*(COMMON)
_ebss = .;
} > FRSRAM
...
_heap = .;
_eheap = ORIGIN(FRSRAM) + LENGTH(FRSRAM);
So, heap comes after the .bss
segment and potentially goes on until the end of memory. The best you can do is to use some of the Contiki memory usage reduction techniques to reduce the size of the .data
and .bss
segments and in this way get more space for the heap.
More to the point, malloc()
is not used by the Contiki operating system and is discouraged for user applications. You are recommended to rewrite the code without dynamic memory allocation, or look for another hardware, highly preferably with MPU.
There is a good reason for this avoidance of malloc and friends. The heap and stack regions share the same memory space and while one grows downwards, the other grows upwards (they "meet in the middle"). When they start to overlap, bad things start to happen. malloc'ing as much memory as possible is a recipe for trouble - later the stack may grow and corrupt your malloc'ed memory.