Dynamic memory management
Let's examine how the heap is used for dynamically allocated memory.
You request memory buffers or blocks of a particular
size from the runtime environment by using
malloc(),
realloc(),
or
calloc(),
and you release them back to the runtime environment when you no longer need them by using
free().
The C++ new
and delete
operators are built on top of
malloc() and free(), so this discussion applies to them as well.
The memory allocator ensures that your requests are satisfied by managing a region of the program's memory area known as the heap. In this heap, the allocator tracks all of the information—such as the size of the original block—about the blocks and heap buffers that it has allocated to your program, so that it can make the memory available to you during subsequent allocation requests. When a block is released, the allocator places it on a list of available blocks called a free list. It usually keeps the information about a block in the header that precedes the block itself in memory.
The runtime environment grows the size of the heap when it no longer has enough memory available to satisfy allocation requests, and it may return memory from the heap to the OS when the program releases memory.