2021-11-29 01:13 PM
I am running Audio_playback_and_record example(shipped with IDE) into which I have integrated my neural network code . The code has malloc and when I try to execute the process function in loop , It stops at HardFault_Handler when trying to malloc.
For each malloc it tries to allocate the memory address instead of using the freed memory.
I have seen in few posts that sbrk is not implemented properly which might cause this issue(link).
Can you clarify the same ?
Can we use malloc for MCUs or should we go for static allocations?
Even though there are no memory overflows for stack and heap why do we see the malloc issue. Is the free implemented correctly here?
2021-11-29 01:33 PM
In GNU/GCC the ST sbrk implementation is pretty minimalistic, and expects the stack and heap to reside within the same memory space.
Got doubts? Look at the source..
malloc/free should work fine, but within the limitations of the MCU, you aren't going to be able to allocate vast tracts of memory, and embedded is particularly vulnerable to issues of leakage and fragmentation of the heap. If you exceed the bounds of the allocated memory you'll corrupt the arena.
The implementation also isn't apt to be thread-safe.
Watch what you're allocating, handle NULL pointer returns properly, and perhaps instrument things so you can follow what's happening and going wrong.
2021-11-30 01:13 AM
Thanks for the reply.
Memory we are allocating are well with in the range . I have allocated sufficient stack and heap size in linker script.
_Min_Heap_Size = 0xffff; /* required amount of heap */
_Min_Stack_Size = 0xffff; /* required amount of stack */
Board has 512KB of RAM and 2 MB of Flash. It is pretty big enough to handle my application. I have manually calculated the stack and memory sizes and updated the above sizes. Attached the reference of map file and list file for reference.
Heap address and stack do not collide because since I have allocated sufficient sizes. I presume it could the heap fragmentation issue. Since with static memory everything works just fine.