C Reallocate Memory
The realloc()
function is used to resize a previously allocated memory block. It adjusts the size of the block while preserving its content up to the minimum of the old and new sizes.
Key Topics
1. Using realloc()
Example: Expanding a Memory Block
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(2 * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
ptr[0] = 10;
ptr[1] = 20;
ptr = (int *)realloc(ptr, 4 * sizeof(int));
if (ptr == NULL) {
printf("Reallocation failed!\n");
return 1;
}
ptr[2] = 30;
ptr[3] = 40;
for (int i = 0; i < 4; i++) {
printf("Value at index %d: %d\n", i, ptr[i]);
}
free(ptr);
return 0;
}
Code Explanation: The realloc()
function resizes the memory block to hold four integers. Existing values are preserved, and new values are added to the extended portion.