0
0
Cprogramming~5 mins

realloc function

Choose your learning style9 modes available
Introduction

The realloc function helps you change the size of a memory block you already reserved. It lets you grow or shrink your memory without losing the data you stored.

When you start with a small array but later need to store more items.
When you want to reduce memory usage by shrinking a previously allocated block.
When you don't know the exact amount of memory needed at the start.
When you want to resize a buffer while reading data from a file or user input.
When you want to adjust the size of a dynamic data structure like a list or stack.
Syntax
C
void *realloc(void *ptr, size_t new_size);

If ptr is NULL, realloc works like malloc.

If new_size is zero, behavior depends on the system; it may free the memory and return NULL or return a unique pointer that can be freed.

Examples
This allocates memory for 5 integers, similar to malloc.
C
int *arr = realloc(NULL, 5 * sizeof(int));
This resizes the previously allocated array to hold 10 integers.
C
arr = realloc(arr, 10 * sizeof(int));
This shrinks the array to hold only 3 integers.
C
arr = realloc(arr, 3 * sizeof(int));
Sample Program

This program starts with an array of 3 integers, then uses realloc to increase its size to 5. It adds two more numbers and prints all 5.

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

int main() {
    int *numbers = malloc(3 * sizeof(int));
    if (numbers == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initialize array
    for (int i = 0; i < 3; i++) {
        numbers[i] = i + 1;
    }

    // Resize array to hold 5 integers
    int *temp = realloc(numbers, 5 * sizeof(int));
    if (temp == NULL) {
        printf("Reallocation failed\n");
        free(numbers);
        return 1;
    }
    numbers = temp;

    // Add new values
    numbers[3] = 4;
    numbers[4] = 5;

    // Print all values
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    free(numbers);
    return 0;
}
OutputSuccess
Important Notes

Always check if realloc returns NULL to avoid losing your original memory pointer.

If realloc fails, the original memory block remains valid and must be freed later.

Using realloc can move the memory block to a new location, so always assign its return value back to your pointer.

Summary

realloc changes the size of a memory block while keeping its data.

Use it to grow or shrink dynamic arrays or buffers.

Always check for NULL to handle memory errors safely.