Lesson 29 / 38
malloc, calloc, realloc, free
Allocate and release heap memory at runtime with malloc, calloc, realloc and free.
By Rahul Agarwal · 15 years in web development · Updated 1 Oct 2026
The heap vs the stack
Local variables live on the stack and vanish automatically. The heap is memory you request explicitly with malloc-family functions, and it stays reserved until you free it.
malloc + free
malloc(n) returns raw, uninitialised memory (or NULL on failure). Always pair it with free once done.
int *arr = malloc(5 * sizeof(int));
if (arr == NULL) {
return 1; // allocation failed
}
for (int i = 0; i < 5; i++) arr[i] = i * i;
printf("%d\n", arr[4]);
free(arr);
arr = NULL;
Output:
16
calloc vs realloc
calloc(n, size) allocates and zeroes the memory. realloc(ptr, newSize) grows or shrinks an existing block, copying old data over — always reassign its result, since the block may move.