Dynamic Memory Allocation Jhalak
Dynamic Memory Allocation Jhalak
Allocation
malloc() takes one argument that is, number of calloc() take two arguments those are: number
bytes. of blocks and size of each block.
syntax of malloc(): syntax of calloc():
void *malloc(size_t n); void *calloc(size_t n, size_t size);
Allocates n bytes of memory. If the allocation Allocates a contiguous block of memory large
succeeds, a void pointer to the allocated enough to hold n elements of size bytes each.
memory is returned. Otherwise NULL is The allocated region is initialized to zero.
returned.
malloc is faster than calloc. calloc takes little longer than malloc because of
the extra step of initializing the allocated
memory by zero. However, in practice the
difference in speed is very tiny and not
recognizable.
Write a C program to find sum of n elements entered by user. To perform this
program, allocate memory dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; i++)
{
scanf("%d", ptr + i);
sum = sum + *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
REALLOC() FUNCTION IN C
•realloc () function modifies the allocated memory
size by malloc () and calloc () functions to new
size.
•If enough space doesn’t exist in memory of
current block to extend, new block is allocated for
the full size of reallocation, then copies the
existing data to new block and then frees the old
block.
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of new size.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; i++)
{
printf("%u\t",ptr + i);
}
printf("\nEnter new size of array: ");
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; i++)
{
printf("%u\t", ptr + i);
}
return 0;
}
FREE() FUNCTION IN C