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.
realloc function
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.
malloc.int *arr = realloc(NULL, 5 * sizeof(int));
arr = realloc(arr, 10 * sizeof(int));
arr = realloc(arr, 3 * sizeof(int));
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.
#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; }
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.
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.