Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to demonstrate the function realloc function

C Code Example — Structure Programs

ADVERTISEMENT

C Program to demonstrate the function realloc function

Objective

Write a C program to demonstrate the realloc function for dynamic arrays.

Algorithm / Approach

  1. Allocate an initial block of memory for n1 integers using malloc.
  2. Print the memory addresses to prove they exist.
  3. Prompt the user for a new array size n2.
  4. Use ptr = realloc(ptr, n2 * sizeof(int)) to resize the block.
  5. 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 realloc call is missing the * sizeof(int) multiplier in the second argument. It should be realloc(ptr, n2 * sizeof(int)). Passing just n2 allocates 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 calling realloc. The provided code calls realloc(ptr, n2) instead of realloc(ptr, n2 * sizeof(int)), which results in massive memory corruption!
ADVERTISEMENT