Skip to main content

IAR Embedded Workbench for RL78 5.20

Dynamic memory on the heap

In this section:

Memory for objects allocated on the heap will live until the objects are explicitly released. This type of memory storage is very useful for applications where the amount of data is not known until runtime.

In C, memory is allocated using the standard library function malloc, or one of the related functions calloc and realloc. The memory is released again using free.

In C++, a special keyword, new, allocates memory and runs constructors. Memory allocated with new must be released using the keyword delete.

The compiler supports heaps in more than one memory type:

Memory type

Memory attribute

Section name

Used by default in data model

Near

__near

NEAR_HEAP

near

Far

__far

FAR_HEAP

far

Huge

__huge

HUGE_HEAP

huge

Table 55. Heaps supported in memory types


In DLIB, to use a specific heap, add the memory attribute in front of malloc, free, alloc, and realloc, for example __near_malloc. The default functions will use of the specific heap variants, depending on project settings such as data model.

For information about how to set up the size for heap memory, see Setting up heap memory.

Potential problems

Applications that use heap-allocated data objects must be carefully designed, as it is easy to end up in a situation where it is not possible to allocate objects on the heap.

The heap can become exhausted if your application uses too much memory. It can also become full if memory that no longer is in use was not released.

For each allocated memory block, a few bytes of data for administrative purposes is required. For applications that allocate a large number of small blocks, this administrative overhead can be substantial.

There is also the matter of fragmentation—this means a heap where small pieces of free memory are separated by memory used by allocated objects. It is not possible to allocate a new object if no piece of free memory is large enough for the object, even though the sum of the sizes of the free memory exceeds the size of the object.

Unfortunately, fragmentation tends to increase as memory is allocated and released. For this reason, applications that are designed to run for a long time should try to avoid using memory allocated on the heap.