Atmel CAVR-4 Manuale Utente
CAVR-4
Part 1. Using the compiler
Data storage
25
Dynamic memory on the heap
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.
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++, there is a special keyword,
new
, designed to allocate memory and run
constructors. Memory allocated with
new
must be released using the keyword
delete
.
The AVR IAR C/C++ Compiler supports having heaps in tiny, near, far, and huge
memory. For more information about this, see The return address stack, page 43.
memory. For more information about this, see The return address stack, page 43.
Potential problems
Applications that are using heap-allocated objects must be designed very carefully,
because it is easy to end up in a situation where it is not possible to allocate objects on
the heap.
because 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 because your application simply uses too much
memory. It can also become full if memory that no longer is in use has not been released.
memory. It can also become full if memory that no longer is in use has not been 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.
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 sections of free
memory is separated by memory used by allocated objects. It is not possible to allocate
a new object if there is no piece of free memory that is large enough for the object, even
though the sum of the sizes of the free memory exceeds the size of the object.
memory is separated by memory used by allocated objects. It is not possible to allocate
a new object if there is no piece of free memory that 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.
Hence, applications that are designed to run for a long time should try to avoid using
memory allocated on the heap.
Hence, applications that are designed to run for a long time should try to avoid using
memory allocated on the heap.