FreeRTOS Memory Management

Hello;

  • I found a memory management problem. In the pvPortMalloc function,
    pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );

It should be changed to :

pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT -1 ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );

  • If the memory happens to be aligned, you don’t need to align it.

for exapmle:
In the case of heap1. heap2,heap4 and heap5 have problems, too

uint8_t ucHeap[configTOTAL_HEAP_SIZE] attribute((at(0x2000A000)));
pbuffer = pvPortMalloc(2);

turn out:
pbuffer = 0x2000a008

It should be a 0x2000a000 instead of a 0x2000a008

  • If it’s heap2, heap4 and heap5:
    uint8_t ucHeap[configTOTAL_HEAP_SIZE] attribute((at(0x2000A000)));
    pbuffer = pvPortMalloc(2);

turn out:
pbuffer = 0x2000a010

It should be a 0x2000a008 instead of a 0x2000a010

Any feedback would be greatly appreciated.
Thanks

1 Like

Apologies for the time taken to reply - I wanted to write some tests for this.

I concur the heap_1 and heap_2 alignment calculation can unnecessarily waste a word, so will create a pull request to amend as per your suggestion (unless you want to create the pull request here first of course :wink: https://github.com/FreeRTOS/FreeRTOS-Kernel

However I don’t see anything wrong in the case of heap_4 or heap_5 where the code is:

if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
{
	xAddress += ( portBYTE_ALIGNMENT - 1 );
	xAddress &= ~portBYTE_ALIGNMENT_MASK;

	/* Adjust the size for the bytes lost to alignment. */
	xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress;
}
1 Like
  • Yes, yesterday I saw no problem with heap_4 and heap_5.
  • Will heap 1 and heap 2 be modified later

Looking at this further, unfortunately the modification does not work when portBYTE_ALIGNMENT is 1. We could use the same technique as heap_4 and heap_5, but really heap_1 and heap_2 are basically obsolete (heap_1 by the ability to use static allocation and heap_2 by heap_4) and as this is only wasting one word of memory I’m inclined to leave the code as is.