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.
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.
Have fun learning :-)
Copyright © 2014 - 2019 DYclassroom. All rights reserved.
rendered in 0.0145 sec