CC Explainer
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 once
STACKautomaticfast, LIFOsmall (~1 MB)frees on returnHEAPmanual / newlargelifetime = youfree / delete
stack 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 all
TIP
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) avgmay occasionally sbrk / mmap
free(p)O(1) avgmay coalesce adjacent free blocks
realloc growO(n)copies if it must relocate
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;
}