C realloc()
In this page:
Introduction to realloc()
This is the tool of choice when you don't know an array's final size upfront -- for example, reading an unknown number of lines from a file and growing a dynamic array to fit as you go, doubling its capacity each time it fills up.
Example: Introduction to realloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(2 * sizeof(int));
arr = realloc(arr, 4 * sizeof(int));
arr[3] = 99;
printf("%d", arr[3]);
free(arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Expanding Allocated Memory
Because the system may need to find a larger contiguous free block elsewhere in memory, realloc() can change the pointer's actual address -- any old pointers or references into the original block become invalid after a successful call.
Example: Expanding Allocated Memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(2 * sizeof(int));
arr[0] = 1; arr[1] = 2;
arr = realloc(arr, 5 * sizeof(int));
printf("%d", arr[0]);
free(arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Shrinking Allocated Memory
The bytes beyond the new smaller size are discarded, but unlike freeing and reallocating from scratch, shrinking in place (when possible) avoids the overhead of copying the remaining data to a new location.
Example: Shrinking Allocated Memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(5 * sizeof(int));
arr = realloc(arr, 2 * sizeof(int));
printf("%zu bytes", 2 * sizeof(int));
free(arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Handling realloc() failures safely
This failure behavior is exactly why you should never write ptr = realloc(ptr, newSize) directly -- if it fails and returns NULL, you've just overwritten your only reference to the original valid block, causing a memory leak.
Example: Handling realloc() failures safely
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(2 * sizeof(int));
int *temp = realloc(arr, 4 * sizeof(int));
if (temp != NULL) {
arr = temp;
}
printf("%d", arr != NULL);
free(arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Best practices with realloc()
Since each reallocation potentially involves copying the entire block's contents to a new address, growing an array one element at a time in a loop is much slower than growing it in larger chunks (like doubling capacity) less often.
Example: Best practices with realloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int capacity = 2;
int *arr = malloc(capacity * sizeof(int));
capacity *= 2;
arr = realloc(arr, capacity * sizeof(int));
printf("%d", capacity);
free(arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: