Static memory allocation vs Dynamic memory allocation in C
In our previous article, We have looked at the pointers and pointer programs. In today’s article, We will look at what is Static Memory allocation and Dynamic memory allocation and what are the differences between static memory allocation vs dynamic memory allocation in C programming
📢 This tutorial is part of the C Programming Language Tutorial series.
Static memory allocation vs Dynamic memory allocation in C language:
Static Memory Allocation in C:
Why it is called static memory allocation? Because we need to specify the exact size of the array or string during the variable creation and we can’t modify the size during the program execution i.e runtime.
For example, you have an array of people’s ages. We don’t know how many people are in an area, So we go ahead and create an array with a size 500 hoping it will hold all people’s details.
Now the array can hold at max 500 elements (Ages), It is fixed and we can’t change the array size during the program execution (Runtime).
What if the array size 500 is very small and we have around 10000 people in the area, Then the array won’t be in the position to hold the details of all people.
Similarly, What if the array size is very large and we have only 100 people in the area, Then we are wasting a lot of memory(RAM).
In both cases, The fixed size of the array is causing the problems. To overcome these problems, We use dynamic memory allocation in C language.
📢 The fixed size of the array is causing problems. To overcome these problems, We use dynamic memory allocation in C language.
Dynamic Memory Allocation in C Programming Language:
The process of allocating and de-allocating the memory during the program execution or runtime is called Dynamic Memory Allocation.
The C programming language supports dynamic memory allocation and it exposes a few library functions to allocate and de-allocate the memory during the runtime.
Unlike other variables, The dynamically allocated memory is stored in the Heap section of the RAM(Program Memory).
📢Remember to free the allocated memory properly. Otherwise, It will cause memory leaks.
We can allocate the memory using the functions like malloc(), calloc(), and realloc(). Similarly, We can de-allocate the memory using the free() function in C language. All these functions are available as part of the stdlib.h header file.
We are going to discuss all the above functions in detail in the following articles, please go through them to learn more about the dynamic memory allocation in c programming language.