Using realloc
What you'll learn: How realloc can allocate new memory, how to handle reallocation safely, and why you must always use free for deallocation.
Acting like malloc
The realloc function is typically used to resize an existing memory block. However, if you pass NULL as the pointer argument alongside a size n greater than zero (n > 0), realloc(NULL, n) behaves exactly like malloc(n). It allocates a fresh block of memory of the requested size.
#include <stdlib.h>
int main(void) {
// Behaves like malloc(5 * sizeof(int))
int *arr = realloc(NULL, 5 * sizeof(int));
if (arr != NULL) {
free(arr);
}
return 0;
}
This behavior is highly useful in loops for growing arrays: if the array pointer starts as NULL, realloc handles the initial allocation automatically.
Additionally, realloc(NULL, 0) behaves like malloc(0): it returns either NULL or a unique pointer that must not be dereferenced (which can still be safely passed to free).
Never use realloc as free
Older codebases sometimes attempt to deallocate memory by passing a size of 0 to realloc with an existing pointer. Do not do this. Free memory with free(ptr).
In C23, realloc(ptr, 0) for a non-null ptr is undefined behavior. Even before C23 (C17/C11) it was implementation-defined whether realloc(ptr, 0) returns NULL (and whether the old object is freed) or a non-null pointer; portable code must never rely on it.
Always use a temporary pointer
When using realloc to resize an existing block of memory, always assign realloc results to a temporary to avoid leaks on failure. If realloc fails, it returns NULL and leaves the old memory intact. If you assign the result directly back to your only pointer, you will overwrite it with NULL, losing the reference to the old memory and creating a memory leak.
#include <stdlib.h>
int main(void) {
int *arr = malloc(5 * sizeof(int));
if (!arr) return 1;
// Always assign realloc results to a temporary to avoid leaks on failure
int *temp = realloc(arr, 10 * sizeof(int));
if (temp == NULL) {
// On failure, the original 'arr' is untouched and must be freed
free(arr);
return 1;
}
// On success, update 'arr' to the new block
arr = temp;
free(arr);
return 0;
}
Key takeaway: realloc(NULL, n) allocates new memory like malloc, but you must always assign its result to a temporary pointer, and always use free(ptr) to deallocate memory since realloc(ptr, 0) is undefined behavior.