While publishing data through MQTT, not able to allocate memory even when desired number of bytes are free

I am using FreeRTOS MQTT V2.1.1 for my application and when trying to publish data it needs to create a copy of my data which requires ~15.2KB of space. Even if more than ~16KB of space is available in the heap still it fails to allocate memory.

I first get the available number of bytes in the heap by xPortGetFreeHeapSize() to make sure enough memeory is available. It returns 16424 as free heap bytes, but when _IotMqtt_SerializePublish() tries to allocate memory using IotMqtt_MallocMessage(15128) it goes to vApplicationMallocFailedHook() indicating ‘Malloc failed to allocate memory’.

Can someone explain why this is happening and is there any workaround for this.

I am using TI CC3220SF-LaunchXL board with FreeRTOS 202002, Simplelink SDK v2.10.00.04

One possible reason is heap fragmentation - the heap has enough memory but not in one contiguous block. You should be able to step through the code and confirm that. Is it possible for you to increase the heap size?

Hi thanks for the reply,

I have verified that I am facing this issue due to memory fragmentation as “xSizeOfLargestFreeBlockInBytes” in heap stats is less than what is demanded.

Unfortunately increasing heap size is not an option for me, are there any solutions in FreeRTOS to eliminate heap fragmentation?

Will upgrading to heap_5 be a solution for this?

Is it possible to shift the already allocated memory to take up the small free spaces or something?

Thank you.

heap_5 does not anything more than heap_4 to eliminate heap fragmentation. It just allows you to use more than one contiguous blocks of memory as heap.

You’ll need to alter the heap implementation for that.

Do you really need to use heap though? Can you not use a fixed size static buffer of 16K to create your copy of data?