C Program to Reallocate Memory Using realloc()

Introduction

In C programming, dynamic memory allocation allows you to allocate memory at runtime. The realloc() function is used to resize the previously allocated memory block without losing the old data. This can be useful when you need to increase or decrease the size of an allocated memory block based on runtime requirements.

Example:

  • Input: Initially allocate memory for 5 integers, then resize to store 8 integers.
  • Output: Memory reallocated, and the new size of the array is displayed.

Problem Statement

Create a C program that:

  • Allocates memory dynamically for an array using malloc() or calloc().
  • Resizes the allocated memory using realloc() to accommodate more elements.
  • Displays the elements of the reallocated memory.

Solution Steps

  1. Include the Standard Libraries: Use #include <stdio.h> for standard input-output functions and #include <stdlib.h> for dynamic memory allocation functions.
  2. Allocate Initial Memory Using malloc() or calloc(): Allocate memory for a specific number of elements.
  3. Reallocate Memory Using realloc(): Resize the allocated memory to a new size using realloc().
  4. Check if Memory Allocation was Successful: Ensure the pointer returned by realloc() is not NULL.
  5. Input New Elements and Display the Reallocated Memory: Use loops to input and display elements in the newly allocated memory.
  6. Free the Allocated Memory: Use free() to deallocate the memory once it is no longer needed.

C Program to Reallocate Memory Using realloc()

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;
    int n, new_size, i;

    // Step 2: Allocate initial memory using malloc()
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    ptr = (int*)malloc(n * sizeof(int));

    // Step 4: Check if memory allocation was successful
    if (ptr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;  // Exit the program if memory allocation fails
    }

    // Input elements for the initially allocated memory
    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &ptr[i]);
    }

    // Display the current elements
    printf("The current elements are: ");
    for (i = 0; i < n; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    // Step 3: Reallocate memory using realloc()
    printf("Enter the new size of the array: ");
    scanf("%d", &new_size);

    ptr = (int*)realloc(ptr, new_size * sizeof(int));

    // Step 4: Check if memory reallocation was successful
    if (ptr == NULL) {
        printf("Memory reallocation failed.\n");
        return 1;  // Exit the program if memory allocation fails
    }

    // Input new elements if the array size has increased
    if (new_size > n) {
        printf("Enter %d more elements:\n", new_size - n);
        for (i = n; i < new_size; i++) {
            scanf("%d", &ptr[i]);
        }
    }

    // Display the elements in the reallocated memory
    printf("The elements after reallocation are: ");
    for (i = 0; i < new_size; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    // Step 6: Free the allocated memory
    free(ptr);

    return 0;  // Return 0 to indicate successful execution
}

Explanation

Step 2: Allocate Initial Memory Using malloc()

  • The program asks the user to input the number of elements they want to store initially, which is stored in the variable n.
  • The malloc() function is used to allocate memory for n elements. The size of each element is sizeof(int).

Step 4: Check if Memory Allocation was Successful

  • The program checks if ptr is NULL. If it is, it means the memory allocation failed, and the program displays an error message and exits.

Step 3: Reallocate Memory Using realloc()

  • The program asks the user to input the new size of the array, which is stored in the variable new_size.
  • The realloc() function is used to resize the memory block pointed to by ptr to accommodate new_size elements.
  • The pointer ptr is updated to point to the newly allocated memory.

Step 4: Check if Memory Reallocation was Successful

  • The program checks if ptr is NULL after reallocation. If it is, the program displays an error message and exits.

Input New Elements and Display the Reallocated Memory

  • If the new size of the array is larger than the old size, the program prompts the user to input additional elements for the newly allocated space.
  • The program then displays all the elements in the array after reallocation.

Step 6: Free the Allocated Memory

  • The free() function is called to deallocate the memory allocated by malloc() and resized by realloc(). This is important to prevent memory leaks.

Return 0

  • The return 0; statement indicates that the program executed successfully.

Output Example

Example Output:

Enter the number of elements: 3
Enter 3 elements:
1 2 3
The current elements are: 1 2 3
Enter the new size of the array: 5
Enter 2 more elements:
4 5
The elements after reallocation are: 1 2 3 4 5

Conclusion

This C program demonstrates how to reallocate memory using realloc(). It covers basic concepts such as dynamic memory allocation, pointer manipulation, and memory resizing, making it a useful example for beginners learning C programming.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top