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 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.
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.