MBED OS and heap memory issue

MBED OS : 6.0
Board: STM32F746G-DISCO discovery board (32F746GDISCOVERY)

When I try to allocate a large memory block on the heap of MBED OS, it fails and malloc return NULL. Even it has sufficient heap space available.
My Code:
uint8_t *camera_buffer = nullptr;
camera_buffer = (uint8_t *) malloc(57000 );
if(camera_buffer == NULL)
{
printf(“Memory not allocated.”);
}

Here is my code Log :
When I try allocate memory using C malloc, it returns NULL.

My Heap size : 89444 / 195312 bytes
allocating memory to file_buffer of 57000.
Memory not allocated.
Current heap Size 89444 + New malloc size is 57000 = 14,6444 (Expected Total memory size), Which less than 19,5312 byte.

Why it failed to allocate memory?

I believe its BUG of MBED OS.

So, I don’t know why it doesn’t work for you, but one cause might be heap fragmentation. This is when memory has been allocated and freed in a particular order that has caused the heap to become fragmented to the point where you cannot request a block as large as 57000.

I’ve never debugged this problem on MBED. There appears to be a heap stats interface you can enable but I don’t think it will tell you what the largest free block is. You can use it to double check there as much free heap as you think there is.

Yes, I have enabled heap status. I am allocating and releasing heap memory multiple times, before allocating 57,000 memory blocks.

"platform.heap-stats-enabled": true,

How I can check the largest free heap block?
Any other suggestion, How I can fix the issue?

I don’t know if it is possible to check for the largest available heap block, I would be interested in that too.

The fact that you are allocating and releasing multiple blocks before the large allocation points to a fragmentation issue. Try to release the blocks in the reverse order you allocate them. Otherwise try to allocate the large block first.

It would be also interesting to know which heap allocation algorithm is used in Mbed and maybe some guidelines how to use the heap to avoid fragmentation. This topic seems to be overlooked in the documentation, even though many internal libraries use dynamic memory.

Hi,
I have the same question,and have you solved the problem?
thanks

I would recommend using placement new with a statically allocated storage buffer of the needed size.

This way you are always sure that you can construct the object in the dedicated storage.

I solved this problem,I found the mbed_heap_start is the section end address for bss,but I change the lds file use anther start addrs,so I think the heap size is from the start address(I set ) to the end address(I set ) ,but the actual size is bss end address to the end address(I set)