C realloc function

realloc is used to resize a previously allocated memory block. You can increase or decrease the size of the block. If the block needs to be expanded, realloc may move the memory to a new location and copy the old data to the new location.

Syntax:


void* realloc(void* ptr, size_t new_size);

Explanation:

ptr: A pointer to the memory block previously allocated (either by malloc or calloc).

new_size: The new size in bytes.

Returns a pointer to the newly allocated memory, or NULL if the reallocation fails.

Example:


arr = (int*) realloc(arr, 5 * sizeof(int));  // Resize the array to hold 5integers

If arr was previously pointing to a block of 10 integers, this call resizes it to 5 integers. If the reallocation fails, realloc returns NULL.

Complete Example:


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

int main() {
    // Step 1: Allocate memory for an array of 5 integers using malloc
    int* arr = (int*) malloc(10 * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // Step 2: Initialize the array
    for (int i = 0; i < 10; i++) {
        arr[i] = i * 10;  // Fill array with some values
    }

    // Step 3: Print the array
    printf("Array values (after malloc): ");
    for (int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Step 4: Reallocate the array to hold 10 integers
    arr = (int*) realloc(arr, 20 * sizeof(int));
    if (arr == NULL) {
        printf("Reallocation failed!\n");
        return 1;
    }

    // Step 5: Initialize the new elements
    for (int i = 10; i < 20; i++) {
        arr[i] = i * 10;  // Fill new elements with values
    }

    // Step 6: Print the updated array
    printf("Array values (after realloc): ");
    for (int i = 0; i < 20; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Output:

Array values (after malloc): 0 10 20 30 40 50 60 70 80 90
Array values (after realloc): 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190