C Program to Resize Memory Using realloc()

C Program to Resize Memory Using realloc()

Dynamic memory allocation in C provides flexibility by allowing programs to request memory at runtime. Sometimes, the initially allocated memory may not be enough, or you may need to reduce the size of a memory block. The realloc() function allows you to resize previously allocated memory without losing the existing data.

Using realloc() is essential when working with arrays or structures whose size may change based on user input or program logic. In this tutorial, we will explore how to use realloc() effectively, demonstrate examples for both increasing and decreasing memory.

Understanding the Problem

Suppose you allocate memory dynamically using malloc() or calloc() but later discover that you need more (or less) space. Creating a new memory block and copying old data manually is inefficient. realloc() solves this problem by resizing the existing memory block while preserving its contents up to the smaller of the old and new sizes.

For example, if a user initially wants to store 5 integers but then decides to store 10, realloc() allows the array to grow without losing the first 5 elements.

Program 1: Increasing Memory Size

This program demonstrates how to increase the size of a dynamically allocated integer array using realloc(). It preserves the existing data while allowing the user to add new elements to the expanded array.

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

int main() {

    int n, newSize;
    int *arr;

    printf("Enter initial number of elements: ");
    scanf("%d", &n);

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

    if (arr == NULL) {

        printf("Memory allocation failed.\n");
        return 1;

    }

    // Input initial elements
    for (int i = 0; i < n; i++) {

        printf("Enter element %d: ", i + 1);
        scanf("%d", &arr[i]);

    }

    printf("Enter new size of array: ");
    scanf("%d", &newSize);

    // Resize memory using realloc
    arr = (int *) realloc(arr, newSize * sizeof(int));

    if (arr == NULL) {

        printf("Memory reallocation failed.\n");
        return 1;

    }

    // Input new elements if array is larger
    for (int i = n; i < newSize; i++) {

        printf("Enter element %d: ", i + 1);
        scanf("%d", &arr[i]);

    }

    // Print all elements
    printf("Array elements: ");

    for (int i = 0; i < newSize; i++) {
        printf("%d ", arr[i]);
    }

    printf("\n");

    free(arr); // Free memory

    return 0;

}

Here, realloc() increases the memory block while preserving existing elements. The program allows new elements to be added without manually copying data, making memory management simpler and more efficient.

Program 2: Decreasing Memory Size

realloc() can also shrink a memory block, removing any elements beyond the new size. This avoids the need to create a new array and copy data manually.

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

int main() {

    int n, newSize;
    int *arr;

    printf("Enter number of elements: ");
    scanf("%d", &n);

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

    if (arr == NULL) {

        printf("Memory allocation failed.\n");
        return 1;

    }

    // Input elements
    for (int i = 0; i < n; i++) {

        printf("Enter element %d: ", i + 1);
        scanf("%d", &arr[i]);

    }

    printf("Enter new size of array (smaller than %d): ", n);
    scanf("%d", &newSize);

    // Resize memory using realloc
    arr = (int *) realloc(arr, newSize * sizeof(int));

    if (arr == NULL) {

        printf("Memory reallocation failed.\n");
        return 1;

    }

    // Print remaining elements
    printf("Array elements after resizing: ");

    for (int i = 0; i < newSize; i++) {
        printf("%d ", arr[i]);
    }

    printf("\n");

    free(arr); // Free memory

    return 0;

}

In this program, realloc() discards any elements beyond the new size. It efficiently reduces memory usage while keeping the remaining data intact, avoiding unnecessary manual copying.

FAQs

1. What is realloc() in C?
realloc() is a standard library function that resizes a previously allocated memory block. It preserves the existing data up to the smaller of the old and new sizes, allowing programs to safely adjust memory usage at runtime.

2. Can realloc() increase and decrease memory size?
Yes, realloc() can both expand and shrink a memory block. When increasing, it may allocate a new block and copy old data; when decreasing, it discards data beyond the new size while keeping the rest intact.

3. What happens if realloc() fails?
If realloc() fails, it returns NULL and the original memory block remains unchanged. Always check the return value to avoid losing access to the original data and potentially causing a memory leak.

4. How is realloc() different from malloc()?
While malloc() simply allocates a new memory block, realloc() adjusts the size of an existing block and preserves its contents. This makes realloc() ideal for dynamic arrays or structures whose size may change during program execution.

Conclusion

The realloc() function is an essential tool in C for resizing memory dynamically while preserving existing data. It allows programs to efficiently grow or shrink memory blocks as needed, making it ideal for flexible arrays, strings, and other dynamic data structures.

By mastering realloc(), you can write memory-efficient and robust programs that handle variable-sized data safely. Always check for allocation failures and remember to free memory after use to avoid leaks.

References & Additional Resources

The following resources provide theoretical knowledge and practical examples for understanding realloc() and dynamic memory allocation in C.

  1. Kernighan, B. W., & Ritchie, D. M. (1988). The C Programming Language (2nd Edition). Prentice Hall – Comprehensive reference on C fundamentals, including pointers and memory management.
  2. Thareja, R. (2011). Data Structures Using C. Oxford University Press – Covers dynamic memory allocation and its application in data structures.
  3. GeeksforGeeks: realloc() in C – Explains realloc() usage with examples and best practices.
  4. Tutorialspoint: C Dynamic Memory – Overview of memory allocation, deallocation, and resizing techniques in C.
  5. Cprogramming.com: Pointers in C – Beginner-friendly guide to pointers and their role in dynamic memory management.
  6. cplusplus.com: realloc() – Official reference documentation for the realloc() function.

Scroll to Top