Dynamic Memory Allocation
Dynamic Memory Allocation
malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a
pointer of type void which can be casted into pointer of any form.
Syntax of malloc()
1|Page
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4
bytes respectively and the pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates
single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.
Syntax of calloc()
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't
get freed on its own. We must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
2|Page
Example #1: Using C malloc() and free()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
3|Page
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
4|Page
printf("Sum = %d", sum);
free(ptr);
return 0;
}
realloc()
If the previously allocated memory is insufficient or more than required, you
can change the previously allocated memory size using realloc().
Syntax of realloc()
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
5|Page
for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);
6|Page