Dynamic memory
So far every variable had a size known when you wrote the program. But how many lines will a file have? How many users will sign up? For data whose size you only learn while the program runs, C lets you ask for memory on the heap with malloc, and give it back with free. This is manual memory management, the thing Python, Java and Go do for you with a garbage collector.
Stack vs heap
| Stack | Heap | |
|---|---|---|
| What lives there | Local variables and function arguments | Memory you request with malloc |
| Size | Small (typically 8 MB per thread) | As much as the system has |
| Lifetime | Freed automatically when the function returns | Until you call free |
| Speed | Extremely fast | Slower (the allocator has to find space) |
malloc and free
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t n = 5;
int *squares = malloc(n * sizeof *squares); // room for 5 ints
if (squares == NULL) {
fprintf(stderr, "out of memory\n");
return 1;
}
for (size_t i = 0; i < n; i++) squares[i] = (int)(i * i);
for (size_t i = 0; i < n; i++) printf("%d ", squares[i]);
printf("\n");
free(squares); // give the memory back
squares = NULL; // so nobody uses it by accident
return 0;
}0 1 4 9 16
malloc(bytes)returns a pointer to that many bytes of uninitialised memory, orNULLif it fails. Always check.n * sizeof *squaressizes it from the variable itself, so it stays right even if you change the type later.- Every
mallocneeds exactly onefree.
calloc and realloc
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *counts = calloc(4, sizeof *counts); // 4 ints, all set to zero
if (!counts) return 1;
printf("calloc: %d %d %d %d\n", counts[0], counts[1], counts[2], counts[3]);
int *bigger = realloc(counts, 8 * sizeof *counts); // grow to 8 ints
if (!bigger) { free(counts); return 1; }
counts = bigger;
for (int i = 4; i < 8; i++) counts[i] = i * 10;
printf("after realloc: %d %d %d\n", counts[0], counts[5], counts[7]);
free(counts);
return 0;
}calloc: 0 0 0 0 after realloc: 0 50 70
realloc resizes a block, keeping its contents (it may move it to a new address). Assign the result to a temporary first: if it fails it returns NULL, and writing counts = realloc(counts, …) would lose your only pointer to the old block.
A growable array
Here's the pattern behind Python's list, Java's ArrayList and Go's slices: keep a capacity, and double it when it's full:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
size_t len;
size_t cap;
} IntList;
int list_push(IntList *l, int value) {
if (l->len == l->cap) {
size_t new_cap = l->cap ? l->cap * 2 : 4;
int *p = realloc(l->data, new_cap * sizeof *p);
if (!p) return -1;
l->data = p;
l->cap = new_cap;
printf(" (grew to capacity %zu)\n", new_cap);
}
l->data[l->len++] = value;
return 0;
}
void list_free(IntList *l) {
free(l->data);
*l = (IntList){0};
}
int main(void) {
IntList list = {0};
for (int i = 1; i <= 10; i++) {
if (list_push(&list, i * i) != 0) return 1;
}
printf("%zu items:", list.len);
for (size_t i = 0; i < list.len; i++) printf(" %d", list.data[i]);
printf("\n");
list_free(&list);
return 0;
}(grew to capacity 4) (grew to capacity 8) (grew to capacity 16) 10 items: 1 4 9 16 25 36 49 64 81 100
Doubling means only a handful of (slow) reallocations, however many items you add.
Allocating strings and structs
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *name; // allocated separately, so it can be any length
int age;
} Person;
Person *person_new(const char *name, int age) {
Person *p = malloc(sizeof *p);
if (!p) return NULL;
p->name = strdup(name); // malloc + copy (standard since C23)
if (!p->name) { free(p); return NULL; }
p->age = age;
return p;
}
void person_free(Person *p) {
if (!p) return;
free(p->name); // free the inside first…
free(p); // …then the struct
}
int main(void) {
Person *a = person_new("Asha Rao", 31);
if (!a) return 1;
printf("%s is %d\n", a->name, a->age);
person_free(a);
return 0;
}Asha Rao is 31
Returning heap memory from a function is fine (unlike a local variable's address): it lives until freed. Make the rule clear in the function's name and documentation: whoever calls person_new must call person_free. That's ownership, and keeping it clear is most of the job.
The four classic bugs
Manual memory management goes wrong in four ways. Each one is shown below being caught by AddressSanitizer (compile with -fsanitize=address -g), which you should use whenever you test.
1. Memory leak: forgetting to free
#include <stdlib.h>
#include <string.h>
int main(void) {
for (int i = 0; i < 3; i++) {
char *buf = malloc(100);
strcpy(buf, "temporary");
// forgot free(buf)
}
return 0;
}gcc -std=c23 -g -fsanitize=address -o main main.c && ./main==121==ERROR: LeakSanitizer: detected memory leaks Direct leak of 300 byte(s) in 3 object(s) allocated from: SUMMARY: AddressSanitizer: 300 byte(s) leaked in 3 allocation(s).
A leak in a short program is harmless (the OS reclaims everything at exit), but in a server running for weeks, memory grows until it's killed.
2. Use after free
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof *p);
*p = 42;
free(p);
printf("%d\n", *p); // the memory is no longer ours
return 0;
}gcc -std=c23 -g -fsanitize=address -o main main.c && ./main==ERROR: AddressSanitizer: heap-use-after-free on address 0x... at pc 0x... bp 0 READ of size 4 at 0x... thread T0 freed by thread T0 here:
Without the sanitizer this might print 42, or garbage, or crash, or (in an attacker's hands) run their code. Setting p = NULL right after free turns it into an obvious crash instead.
3. Double free
#include <stdlib.h>
int main(void) {
char *p = malloc(10);
free(p);
free(p);
return 0;
}gcc -std=c23 -g -fsanitize=address -o main main.c && ./main==ERROR: AddressSanitizer: attempting double-free on 0x... in thread T0: free(): double free detected in tcache 2 bash: line 1: 198 Aborted ./plain without the sanitizer: exit code 134
Even without the sanitizer, the C library's allocator detected this one and aborted the program (exit code 134 = 128 + SIGABRT). It can't catch every case, though. free(NULL) is always safe, another reason to set pointers to NULL after freeing.
4. Heap buffer overflow
#include <stdlib.h>
#include <string.h>
int main(void) {
char *name = malloc(5);
strcpy(name, "Asha Rao"); // 9 bytes into a 5-byte block
free(name);
return 0;
}gcc -std=c23 -g -fsanitize=address -o main main.c && ./mainmain.c: In function ‘main’:
main.c:6:5: warning: ‘__builtin_memcpy’ writing 9 bytes into a region of size 5 overflows the destination [-Wstringop-overflow=]
6 | strcpy(name, "Asha Rao"); // 9 bytes into a 5-byte block
| ^~~~~~~~~~~~~~~~~~~~~~~~
main.c:5:18: note: destination object of size 5 allocated by ‘malloc’
5 | char *name = malloc(5);
| ^~~~~~~~~
==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x... at pc 0x... bp
WRITE of size 9 at 0x... thread T0Valgrind
Valgrind finds the same problems without recompiling, by running your program in a simulated CPU (about 20–50 times slower):
#include <stdlib.h>
int main(void) {
int *a = malloc(40);
int *b = malloc(80);
free(a);
(void)b; // b is never freed
return 0;
}gcc -g -o leak leak.c
valgrind --leak-check=full ./leaktotal heap usage: 2 allocs, 1 frees, 120 bytes allocated 80 bytes in 1 blocks are definitely lost in loss record 1 of 1 at …: malloc (vg_replace_malloc.c:446) by …: main (leak.c:5) definitely lost: 80 bytes in 1 blocks
It points at the exact line (leak.c:5) that allocated the leaked block.
Habits that prevent memory bugs
- Check every allocation for
NULL. - Pair them: write the
freeas soon as you write themalloc, often in a matching_new/_freepair of functions. - One owner: decide which part of the code frees each block.
p = NULLafterfree(p).- Test with
-fsanitize=address,undefinedand run Valgrind on anything long-running. - Allocate less: a fixed array on the stack or one big block is simpler than many small ones.
Practice
- Read numbers from the user until they type 0, storing them in a growable array, then print them in reverse.
- Write
char *repeat(const char *s, int n)that returns a new string withsrepeatedntimes. Free it inmain. - Write a singly linked list (
struct node { int value; struct node *next; }) with push, print and free functions. Check it with Valgrind. - Take one of the four bugs above, compile it without the sanitizer, and see what happens.
1.What does malloc return when it can't allocate memory?
2.Why is p = realloc(p, n) risky?
3.What is a "use after free"?
4.A struct holds a malloc'd name. In what order do you free?