C · 4 · Dynamic Memory & Data Structures17 / 35 · 49%
malloc & free
Ask the heap for memory. You own it until you free it.
Examples: malloc, calloc, realloc, free
shortcuts: ← prev · → next · M mark
1
Allocate
malloc(n) returns a void* to n bytes of uninitialised memory, or NULL.
Example
example
int *arr = malloc(100 * sizeof *arr);
if (!arr) { perror("malloc"); return 1; }
for (int i = 0; i < 100; i++) arr[i] = i;
// ... use arr ...
free(arr); // must free exactly oncestack vs heap
2
calloc & realloc
calloc zero-initialises. realloc resizes (and may move) an existing block.
Example
example
int *a = calloc(10, sizeof *a); // zeroed
a = realloc(a, 20 * sizeof *a); // grow to 20
if (!a) { /* OOM: original block leaked if you overwrote */ }WATCH OUT
Never do a = realloc(a, ...); without a temporary — you leak on failure.
3
The 3 Deadly Sins
Memory leaks, use-after-free, double-free — all Undefined Behavior.
Example
example
int *p = malloc(4);
free(p);
*p = 1; // use-after-free
free(p); // double-free
// leak: forgot to call free at allTIP
Run under valgrind or AddressSanitizer (-fsanitize=address) to catch all three.
4
Complexity & Try It
malloc is fast on average, but not free — and fragmentation grows with churn.
Complexity
| malloc(n) | O(1) avg | may occasionally sbrk / mmap |
| free(p) | O(1) avg | may coalesce adjacent free blocks |
| realloc grow | O(n) | copies if it must relocate |
Try it liveOpen in Compiler Explorer ↗
run it
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *v = malloc(5 * sizeof *v);
for (int i = 0; i < 5; i++) v[i] = i * i;
for (int i = 0; i < 5; i++) printf("%d ", v[i]);
free(v);
return 0;
}