Dynamic memory allocation lets a program request memory while it runs, when sizes are not known at compile time. The C library provides malloc, calloc, realloc, and free in <stdlib.h>. Memory comes from the heap, which you must release yourself. This section explains the memory layout of a program, stack vs heap, each allocation function, dynamic arrays, 2D arrays, memory leaks, and safe habits.
Every malloc needs a free.
Match each successful allocation with exactly one free. Check allocation results for NULL, and set pointers to NULL after freeing them.
Path
Learning Path
Work through the stages in order, or jump to a topic from the index below (10 tutorials).
A quick taste of dynamic memory. Compile with gcc file.c -std=c11 -Wall -o out.
Example 1 — Allocate, use, and free
Create an array whose size is chosen at run time.
C
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 4;
int *a = malloc(n * sizeof *a);
if (a == NULL) return 1;
for (int i = 0; i < n; i++) a[i] = (i + 1) * 10;
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
free(a);
return 0;
}
Output
10 20 30 40
How It Works
malloc(n * sizeof *a) requests space for n ints.
A NULL result means the request failed.
free(a) returns the memory to the system.
Index
C Dynamic Memory Allocation Topics
Every guide in this section with a one-line summary (10 tutorials).
Memory model
2 tutorials
Where code, globals, the stack, and the heap live.