C Program to demonstrate the function realloc function
Objective
Write a C program to demonstrate the realloc function for dynamic arrays.
Algorithm / Approach
- Allocate an initial block of memory for
n1integers usingmalloc. - Print the memory addresses to prove they exist.
- Prompt the user for a new array size
n2. - Use
ptr = realloc(ptr, n2 * sizeof(int))to resize the block. - Print the new memory addresses.
main.c
#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 : \n");
for(i=0; i < n1; ++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
printf("New Allocated memory :\n");
for(i=0; i < n2;++i)
printf("%u\t",ptr+i);
return 0;
}
Expected Output
Enter size of Array : 5 Address of previously allocated memory : 1002 1006 1010 1014 1018 Enter new size of array : 2 New Allocated memory : 1002 1006
Explanation of the Program
realloc()(Re-allocation) is used when you have already dynamically allocated memory, but you realize you need more (or less) space.- It takes the old pointer and the new required total size. It attempts to expand the memory block in place. If it can't expand it due to adjacent used memory, it safely copies all your existing data to a new, larger location in RAM and gives you the new pointer.
- Note on the provided code: the
realloccall is missing the* sizeof(int)multiplier in the second argument. It should berealloc(ptr, n2 * sizeof(int)). Passing justn2allocates exactly 2 bytes, which is not enough for an integer array!
Complexity
Time Complexity
O(n) - Realloc might have to copy all data to a new location in the worst case.
Space Complexity
O(n) - Based on the new size requested.
Common Mistakes
- Forgetting to multiply the new size by the
sizeof()the data type when callingrealloc. The provided code callsrealloc(ptr, n2)instead ofrealloc(ptr, n2 * sizeof(int)), which results in massive memory corruption!