The dynamic memory that is stored in the heap is used to store data that are created in the middle of the program execution. In general, this type of data can be almost the entire set of data in a program. For example, let us suppose a program that opens a file and reads a set of words. How many are in the file? What is their size? This information cannot be known until the entire information in the file is processed.
Memory manipulation in C is performed with a very simple mechanism yet error prone. The two type of operations are memory request and memory release. The cycle is simple, when a new data is required, memory is requested for as many bytes as required, and once the data is no longer needed, the memory is released to be reused. This scheme is known as “ explicit memory management” because it requires to execute a function to request memory and another one to release it.
The four main functions to manipulate memory in C are:
void *malloc(size_t size)
. It is the
function to reserve as many consecutive bytes in memory as indicated by
its only parameter. It returns the memory address of the reserved
portion. The memory is not initialized to any particular value.
void *calloc(size_t nmemb, size_t size)
. It
reserves space for as many elements as given by the parameter
nmemb
, and each of them with the size given by the second
parameter. In other words, it reserves nmemb * size
consecutive bytes in memory. As in the case of the previous function, it
returns the memory address at the beginning of the reserved
portion. This function does initialize all the bytes with the value
zero.
void free(void *ptr)
. Function that given a
pointer it frees the memory space previously reserved. The pointer given
to this function must have been obtained with a memory allocation
call. It is not necessary to include the size. Once this function is
executed, the data in that memory portion are considered garbage and
therefore can be re-used at any time by the system.
void *realloc(void *ptr, size_t
size)
. Function to re-size a memory portion previously reserved
and pointed to by the first parameter to a new size given as second
parameter. The function returns a memory address of this new resized
portion that does not necessarily need to be identical as the one given
as parameter. The data is kept unmodified in as many bytes as the
minimum between the actual size and the new size.
Answer the following questions to see if you understood what the content of this document: