C
Resize with realloc
Learn to resize an array with realloc.
Resizing with realloc
realloc grows or shrinks a previously allocated block. Signature: void *realloc(void *ptr, size_t new_size);.
Example: arr = realloc(arr, 5 * sizeof(int));. Old content is preserved; new elements are uninitialized. One key point: if realloc fails it returns NULL and the old memory is still valid. So writing arr = realloc(arr, ...) directly is risky; on failure you lose the old address. The safe pattern is to use a temporary pointer.
The safe realloc pattern
Safe realloc uses a temporary pointer. First call tmp = realloc(arr, new_size); if tmp is not NULL, do arr = tmp.
Example: int *tmp = realloc(arr, 5 * sizeof(int)); if (tmp) arr = tmp;. In this pattern, even if realloc fails, arr keeps the old address and free(arr) still works. If the new size is smaller than the old content, the overflow part is lost. Memory management needs care; this pattern is standard for large allocations.
Exercise Grow an array with realloc
Allocate a two-element array with int *arr = malloc(2 * sizeof(int));. Assign arr[0] = 1; arr[1] = 2;. Use the safe realloc pattern to grow it to 4 elements: int *tmp = realloc(arr, 4 * sizeof(int)); if (tmp) arr = tmp;. Assign 3 and 4 to the new two elements. Print all four with printf("%d ", arr[i]) in a for loop, then printf("\n"). Free with free(arr);.
Show example solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *arr = malloc(2 * sizeof(int));
arr[0] = 1;
arr[1] = 2;
int *tmp = realloc(arr, 4 * sizeof(int));
if (tmp) arr = tmp;
arr[2] = 3;
arr[3] = 4;
for (int i = 0; i < 4; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
return 0;
}
Test yourself
-
Match the realloc behaviors
- realloc(NULL, n)
- Behaves like malloc
- realloc(ptr, 0)
- Behaves like free
- realloc(ptr, larger)
- Grows
- realloc fails
- Old block valid
-
What happens if realloc returns NULL?
- Old memory is freed
- The program crashes
- Old memory is still valid
- arr becomes NULL
Show answer
Old memory is still valid — On realloc failure the old block is not freed; it stays valid.
-
Safe realloc pattern
int *tmp = ____(arr, 5 * sizeof(int));
if (tmp) arr = tmp;
Show answer
int *tmp = realloc(arr, 5 * sizeof(int));
if (tmp) arr = tmp;
Next lesson: Memory leaks