realloc() in C - Source Code Example

In this source code example, we will see how to use the realloc() function in C programming with an example.

realloc() Function Overview

In C programming, dynamically allocated memory can be resized as per the requirements using the realloc() function. This function is found in the <stdlib.h> library. 

The realloc() function is used to resize memory that was previously allocated with malloc(), calloc(), or realloc(). It can increase or decrease the memory size, and in case of an increase, it might move the memory block to a new location.

Source Code Example

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

int main() {
    int *arr;
    int n, new_n;

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

    // Using malloc to get memory for 'n' integers
    arr = (int*)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        exit(1);
    }

    printf("Enter %d integers:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Ask user for new size
    printf("Enter new number of elements: ");
    scanf("%d", &new_n);

    // Using realloc to resize memory
    arr = (int*)realloc(arr, new_n * sizeof(int));

    if (arr == NULL) {
        printf("Memory reallocation failed!\n");
        exit(1);
    }

    if(new_n > n) {
        printf("Enter %d more integers:\n", new_n - n);
        for (int i = n; i < new_n; i++) {
            scanf("%d", &arr[i]);
        }
    }

    // Display the integers
    printf("Elements of array are:\n");
    for (int i = 0; i < new_n; i++) {
        printf("%d ", arr[i]);
    }

    // Free the allocated memory
    free(arr);

    return 0;
}

Output

Enter initial number of elements: 3
Enter 3 integers:
1 2 3
Enter new number of elements: 5
Enter 2 more integers:
4 5
Elements of array are:
1 2 3 4 5

Explanation

1. Initially, the user provides how many numbers they want to input, and memory is allocated using malloc.

2. The user then fills in these numbers.

3. Next, the user is asked if they want to change the number of elements.

4. The realloc function is then used to change the size of the allocated memory.

5. If the new size is larger than before, the user is asked to provide more numbers.

6. Finally, we display all numbers and free the memory.

By using realloc, we can efficiently resize memory as per our requirements without the need for manual memory management.


Comments