Home > Mobile >  I am studying 'C' and I getting confused on Static and Dynamic memory allocation
I am studying 'C' and I getting confused on Static and Dynamic memory allocation

Time:11-05

I am trying to find the difference between static and dynamic memory allocation...

This is static memory allocation:

#include<stdio.h>
int main(){
int a;
printf("Enter the size of array: ");
scanf("%d",&a);
int arr[a];
for(int i=0;i<a;i  ){
    arr[i]=i;
}
for(int i=0;i<a;i  ){
    printf("%d\n",arr[i]);
}
return 0;
}

Output:

/tmp/aGaOu4PWEU.o
Enter the size of array: 10
0
1
2
3
4
5
6
7
8
9

When we compile and run this we have to enter value of 'a' during run time and size of array arr[] is also set during run time, but how is it compile time???

CodePudding user response:

What you are using here is a variable length array (VLA for short). It is allocated during runtime, but it is allocated on the stack.

I believe you may confuse static allocation and stack allocation. Static allocation is only possible if the compiler knows the object size at compile time.

CodePudding user response:

A static array is located in a continuous segment of memory, sizeof(int) bytes are allocated for each element of the array, respectively, the amount of memory required to accommodate the entire array is a*sizeof(int) bytes according to your code. This value is limited from above by the platform and the compiler. If an array is declared statically, that is, in the global scope, in the scope of a namespace, or as a static member of a class, then it is allocated in static memory. Arrays declared locally are allocated memory on the stack, which has a limited size. Dynamic arrays are allocated in dynamic memory. For dynamic arrays, there are only operations for creating and deleting them; to work with such arrays, pointers to their beginning are used. The size of such an array must be stored separately, sometimes pointers to the null element are used for this. If a static array is defined as a global variable (i.e., declared outside the body of any function, or with the static modifier), then its size is added to the total size of all uninitialized global variables of the program, the memory for these variables is allocated by the system entirely at the stage downloads. Therefore, the sizes of such arrays can no longer be changed, the compiler needs to know them in advance, which means that only constants are allowed as them.

  •  Tags:  
  • c
  • Related