Memory allocation is an essential concept in programming. It is the process of reserving a space in memory for a variable or data structure. In C Programming, there are two types of memory allocation:
Static and Dynamic.
Static memory allocation is done during compile-time and the memory is allocated during the declaration of the variable. The allocated memory remains constant throughout the program execution. The variables declared statically have a fixed memory location that remains the same throughout the program's lifecycle.
Here is an example of static memory allocation:
#includeint main() {
static int x = 10;
//Static memory allocation printf("The value of x is:
%d", x);
return 0;
}
In the above code, the variable 'x' is declared as a static variable. The memory for 'x' is allocated during compile-time, and it remains fixed throughout the program execution.
Dynamic memory allocation is done during run-time, and the size of the block of memory allocated can be altered during the program's execution. The memory allocated dynamically can be deallocated when it is no longer required, hence making it possible to recycle memory.
Here is an example of dynamic memory allocation:
#include #include int main() {
int *ptr;
ptr = (int*) malloc(5 * sizeof(int));
//Dynamic memory allocation for(int i=0;
i<5;
i++){
printf("Enter a number:
");
scanf("%d",(ptr+i));
}
printf("\nThe numbers entered are:
");
for(int i=0;
i<5;
i++){
printf("%d ", *(ptr+i));
}
free(ptr);
//Freeing the dynamically allocated memory return 0;
}
In the above code, the memory for an integer pointer 'ptr' is dynamically allocated using the 'malloc' function during runtime. Five integer spaces are allocated for the pointer. These five spaces can be accessed using the pointer and can be altered during the program's execution. The memory allocated dynamically must be released when it is no longer required using the 'free' function.
Static memory allocation and dynamic memory allocation are two important concepts in C Programming. Static memory allocation is done during compile-time, and the allocated memory remains fixed throughout the program's lifecycle. Dynamic memory allocation, on the other hand, is done during run-time and can be resized during the execution of the program. The memory allocated dynamically can be deallocated, hence making it possible to recycle memory.