# Error when using vPortFree(ptr) CMSIS-RTOS on STM32F4

I will need to handle dynamic memory using malloc and free. Looking on FreeRTOS documentation, I found pvPortMalloc(size) and vPortFree(ptr) , pvPortMalloc(size) works fine. When try to release memory using vPortFree(ptr) inside a Thread, the code hangs on that call.

I'm using heap_4 for CMSIS-RTOS on TrueStudio.

• Please ask a specific question, and post some code. – laptop2d Apr 1 at 15:28

In FreeRTOS, the way pvPortMalloc() and vPortFree are implemented depends on which of the heap options you've chosen for your project.

heap_1 - the very simplest, does not permit memory to be freed
heap_2 - permits memory to be freed, but does not coalescence adjacent free blocks.
heap_3 - simply wraps the standard malloc() and free() for thread safety
heap_4 - coalescences adjacent free blocks to avoid fragmentation. Includes absolute address placement option
heap_5 - as per heap_4, with the ability to span the heap across multiple non-adjacent memory areas

https://www.freertos.org/a00111.html

Judging by the behavior of your project, it seems that either:

• you have heap_1, and not heap_4 as you intend
• you are corrupting the memory block information for the block you're trying to free

When you malloc some memory, the pointer you get is actually pointing a little way into the actual memory block which was allocated.
The space between the actual start of the block and the pointer you were given is used to store some information about the block and heap which free will use to de-allocate the block and return it to the heap when you're finished with it.
If you corrupt this info, then free will get confused and could easily show the symptoms you describe.

• Thanks for the answer. I did solve the problem, it happens when increment the pointer and try to free after this operation. – Marcelo Gadotti Apr 2 at 17:28