In this tutorial we will learn about dynamic memory allocation in C programming language.
We learned about arrays in the Array tutorial. So, we know that to create an array we have to specify the number of elements in the array before the code is compiled.
If we don't specify the size then we will get an error during code compilation.
Following code will throw an error during compilation.
int arr; // this will throw an error
Also, we will be wasting memory if the size of the array is too big compared to the number of data saved.
And we will also face problem if the size of the array is less than the number of data to be saved.
This is were dynamic memory allocation comes into picture as it allows us to allocate memory at run time.
Following are the functions we use when we want to allocate memory dynamically.
|malloc||This function allocates required number of bytes and returns a pointer to the first byte of the allocated memory location.|
|calloc||This function allocates an array of elements and initializes them to zero and returns a pointer to the allocated memory location.|
|realloc||This function will modify the size of the previously allocated memory location.|
|free||This function will free the previously allocated memory location.|
Following image represents the memory area.
All the program instructions, global and static variables are stored in the memory region called the permanent storage area.
Local variables are stored in the memory region called the stack.
The free memory area between the permanent storage area and stack is called the heap. This is the area available for the dynamic allocation during the execution of the program.
The size of the heap keeps changing during the program execution due to the creation and removable of variables that are local to functions and blocks.
So, a common problem we can encounter is overflow of memory during dynamic memory allocation.
The above mentioned memory allocation functions returns
NULL when there is no sufficient memory space for allocation.