Preview
Dynamic memory allocation in C
We can dynamically allocate and de-allocate memory to variables in C language. Different functions for dynamic memory allocation/de-allocation are:
- malloc()
- free()
1. malloc() function
malloc() is a predefined function of C language that can dynamically allocate memory to variables. It allocates a block of fixed size block from memory. Header file required for malloc() function is stdlib.h.
Example
int *ptr;
ptr=malloc(sizeof(int));
ptr is a pointer that is allocated memory of 2 because sizeof(int) is assumed to return 2 bytes.
Program of malloc(). |
#include<stdio.h> #include<stdlib.h> int main() { int *ptr;ptr = malloc(sizeof(int)); *ptr=5;printf(“*ptr=%d”,*ptr); free(ptr); } |
Output |
*s=15 |
2. free() function
This function is used to deallocate memory dyanamically assigned to a variable by using malloc() function.
Example:
free(ptr);
This command will dealloacte memory assigned to pointer variable ptr. It has been demonstrated in above program.