A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
You allocated an array for 10 elements. Now you need 20. Without realloc, you allocate a new block, copy the old data, free the old block, and update your pointer. realloc does all of that in one call. If the heap has room to extend the existing block, it does so in place with no copy. If not, it allocates a new block, copies, frees the old, and returns the new address. Either way, your data survives.
#include <stdio.h>#include <stdlib.h>int main(void) {int capacity = 4;int *arr = malloc(capacity * sizeof(int));if (arr == NULL) return 1;for (int i = 0; i < capacity; i++) {arr[i] = i + 1;}printf("Before realloc (cap=%d): ", capacity);for (int i = 0; i < capacity; i++) printf("%d ", arr[i]);printf("\n");int new_capacity = 8;int *tmp = realloc(arr, new_capacity * sizeof(int));if (tmp == NULL) {fprintf(stderr, "realloc failed\n");free(arr);return 1;}arr = tmp;capacity = new_capacity;for (int i = 4; i < capacity; i++) {arr[i] = i + 1;}printf("After realloc (cap=%d): ", capacity);for (int i = 0; i < capacity; i++) printf("%d ", arr[i]);printf("\n");free(arr);return 0;}
Never write arr = realloc(arr, new_size). If realloc fails, it returns NULL. Your original pointer is overwritten with NULL. The old block is still allocated but you have lost the only reference to it. That is a memory leak and a dangling situation simultaneously. Always assign to a temporary, check for NULL, then update the original.
arr = realloc(arr, size) is the most common realloc bug in C code. It leaks memory on failure and leaves you with a NULL pointer. The temporary-variable pattern (tmp = realloc(arr, size); if (tmp) arr = tmp;) costs one extra line and eliminates the bug entirely.
realloc can shrink a block. The excess data is discarded. Passing NULL as the first argument is equivalent to malloc: realloc(NULL, size) allocates a new block. Passing 0 as the size is implementation-defined: it may free the block and return NULL, or return a unique pointer. Avoid relying on either behavior.
realloc is the foundation of dynamic arrays, string builders, and any data structure that grows at runtime. The temporary-pointer pattern is non-negotiable. Next: a security vulnerability specific to realloc that appears in real CVEs.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.