Keil Logo

ARMCLANG: Extend heap to use different memory regions


Information in this knowledgebase article applies to:

  • MDK v5.x
  • Arm compiler toolchain v5.x and v6.x
  • Cortex-M devices

QUESTION

My program requires big heap memory allocation. The internal RAM size on my target device is quite limited. But there is enough space in external RAM memory region, which can be used together with the internal RAM for heap memory allocation. How can I use external RAM as heap for my program?

ANSWER

If you want to utilize different memory regions, such as external RAM memory assuming it has been properly initialized, as the heap of your program, you can create a execution region in your scatter file, such as

RW_ERAM1 0x60000000 0x00020000  {  ; RW data
   *.o (HEAP)
}

where the base address of the heap is defined at the address 0x60000000 with a total size of 0x00020000 bytes.

Then the heap size configured in the startup_xxx.s startup file can be as big as the size of RW_ERAM1 execution region.

If you want to extend heap size at runtime instead of built time, a function __user_heap_extend() can be defined as follows, which is called by the runtime library automatically, when there is no sufficient free heap space for a call of malloc(). Note that it is not called by user code directly.

char ExtraHeap[ 0xC00 ] ;

__attribute__( ( used ) ) unsigned __user_heap_extend( int var0, void **base, unsigned requested_size )
{
  unsigned RetVal ;

  if( sizeof( ExtraHeap ) >= requested_size )
  {
    *base = ExtraHeap ;
    RetVal = sizeof( ExtraHeap ) ;
  }
  else
  {
    RetVal = 0 ;
  }

  return( RetVal ) ;
}

Since the runtime library only has a weak reference to __user_heap_extend(), in order to avoid it being removed by armlink due to linker optimization, __attribute__( ( used ) ) should be added to the function definition.

MORE INFORMATION

Last Reviewed: Thursday, April 18, 2019


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.