Go back

Data Structures and Algorithms - Dynamic Memory Allocation

In C we can allocate memory in runtime, which is known as Dynamic memory allocation.

In C we can do dynamic memory allocation using two functions -

Both of these functions come from the library #include<stdlib.h>

Both of these functions return a void pointer which need to be typecasted to the pointer we can use.

Example

int *p = (int*) malloc(sizeof(int)); // 1 integer
int *p = (int*) calloc(5, sizeof(int)); // array of 5 integers

After use of a memory we also need to free the memory otherwise it can cause memory leak. So we use the free() fucntion.