Static Memory Allocation In C Programming😀

Introduction

In this article, we are going to discuss static memory allocation.

The static memory allocation is a fixed amount of memory that is allocated during the compile time of a program and the stack data structure.

There are different types of memory architectures available in C language and memory is allocated in two areas, either in the stack memory area or the heap memory area.

When the memory allocated at compile time is going to store in stack memory it is known as static memory allocation, and when the memory allocated at runtime is stored in heap memory it is known as dynamic memory allocation.

All local variables are stored in stack memory at compile-time and all pointer variables are stored in heap memory at the runtime of a program

STATIC MEMORY ALLOCATION IN C Programming 

Now let’s discuss deeply static memory allocation

In static memory allocation, memory allocated is fixed which cannot be changed or altered after allocation.

For better memory management, memory requirements must be known before memory allocation.

For example, the array declaration is an example of a static memory allocation and the size of the array must be known beforehand. You cannot change the size of the array once the memory is allocated.

Let’s understand this with the help of the example in C programming.

#include<stdio.h>
void main(){
 int x[35], i;
 for(i=0;i<35;i++){
 cin>>x[i];
 }
 for(i=0;i<35;i++){
 cout<<x[i];
 }
}

In the above code snippet, the declaration of the array is static in nature, and memory is allocated at compile time itself.

This is an example of static memory allocation because the size of the array is fixed, i.e., size is 35 as demonstrated by int x[35]. You cannot alter the size of the array at the runtime of the program.

That’s all about static memory allocation.

Let’s now discuss static memory deletion and the disadvantages of static memory allocation.

Deletion of static memory is totally dependent on the scope of a variable. As soon as the scope of the variable is over, allocated memory gets freed.

The disadvantages of static memory allocation Most of the time static memory allocation results in wastage of the memory, which cannot be freed when it is no longer needed.

For example, let’s assume you declare an array of size 45 at compile time but at runtime, you need to add only 12 elements into the array.

In this scenario, the reserved memory for the next thirty-three elements gets wasted. Or, let’s say you declare an array of size 35 at compile-time, but at runtime, you need to add 7 extra elements into the array. In this case, the size of the array cannot be increased.

That’s the disadvantage of static memory allocation.

Happy Reading :)