C Memory Management
So far every variable has had a size fixed when you wrote the program. But often you only find out at run time how much data there is: a file with an unknown number of lines, a list that grows as the user adds items. For this, C lets you request memory dynamically from an area called the heap, and gives you full responsibility for returning it.
Stack vs. heap
| Stack | Heap | |
|---|---|---|
| Used for | local variables, function parameters | memory you request with malloc & co. |
| Size decided | at compile time | at run time |
| Lifetime | until the function/block ends | until you call free |
| Managed by | the compiler, automatically | you, manually |
| Typical size limit | a few megabytes | most of the available RAM |
All of the heap functions live in <stdlib.h>.
malloc: allocate memory
malloc(bytes) reserves a block of the given size and returns a pointer to its start, or NULL if the request cannot be satisfied. The memory is not initialised — it contains garbage until you write to it.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5;
int *squares = malloc(n * sizeof(int)); // room for 5 ints
if (squares == NULL) {
printf("Out of memory!\n");
return 1;
}
for (int i = 0; i < n; i++) {
squares[i] = (i + 1) * (i + 1); // use it like an array
}
for (int i = 0; i < n; i++) {
printf("%d ", squares[i]);
}
printf("\n");
free(squares); // give it back
squares = NULL;
return 0;
}1 4 9 16 25
Always compute the size with sizeof — n * sizeof(int) or, even safer, n * sizeof *squares, which stays correct if you later change the pointer's type.
free: release memory
Every block you get from malloc, calloc or realloc must be passed to free exactly once when you no longer need it. Setting the pointer to NULL afterwards protects you from accidentally using it again.
| Mistake | Name | Result |
|---|---|---|
never calling free |
memory leak | program uses more and more memory |
using memory after free |
use-after-free | garbage values, crashes, security holes |
calling free twice on the same block |
double free | heap corruption, crash |
freeing something not from malloc |
invalid free | crash |
free(NULL) is allowed and does nothing, which is why resetting pointers to NULL is a safe habit.
calloc: allocate zeroed memory
calloc(count, size) allocates room for count elements of size bytes and sets every byte to zero:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *text = "mississippi";
int *counts = calloc(26, sizeof *counts); // one counter per letter, all 0
if (counts == NULL) return 1;
for (int i = 0; text[i] != '\0'; i++) {
counts[text[i] - 'a']++;
}
for (int c = 0; c < 26; c++) {
if (counts[c] > 0) {
printf("%c: %d\n", 'a' + c, counts[c]);
}
}
free(counts);
return 0;
}i: 4
m: 1
p: 2
s: 4
realloc: grow or shrink a block
realloc(ptr, new_size) changes the size of an existing block. It may need to move the data to a new location, so it returns a (possibly different) pointer. The old contents are preserved up to the smaller of the two sizes.
A growing array — the C equivalent of a list or vector — doubles its capacity whenever it runs out of room:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int capacity = 2;
int size = 0;
int *data = malloc(capacity * sizeof *data);
if (data == NULL) return 1;
for (int value = 10; value <= 100; value += 10) {
if (size == capacity) {
capacity *= 2;
int *bigger = realloc(data, capacity * sizeof *data);
if (bigger == NULL) { // data is still valid here
free(data);
return 1;
}
data = bigger;
printf("grew to capacity %d\n", capacity);
}
data[size++] = value;
}
printf("%d values:", size);
for (int i = 0; i < size; i++) printf(" %d", data[i]);
printf("\n");
free(data);
return 0;
}grew to capacity 4
grew to capacity 8
grew to capacity 16
10 values: 10 20 30 40 50 60 70 80 90 100
Watch out: Never write
data = realloc(data, ...)directly. Ifreallocfails it returnsNULLbut leaves the old block alone — and you would have just overwritten your only pointer to it, leaking the memory. Use a temporary pointer as above.
Allocating structures and strings
Dynamic memory is especially useful for structures whose number or size is unknown in advance, and for copies of strings:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *name; // points to heap memory sized exactly for the name
int age;
} Person;
Person *person_new(const char *name, int age) {
Person *p = malloc(sizeof *p);
if (p == NULL) return NULL;
p->name = malloc(strlen(name) + 1); // +1 for the '\0'
if (p->name == NULL) {
free(p);
return NULL;
}
strcpy(p->name, name);
p->age = age;
return p;
}
void person_free(Person *p) {
if (p != NULL) {
free(p->name); // free the inner block first
free(p);
}
}
int main(void) {
Person *a = person_new("Hedy Lamarr", 41);
Person *b = person_new("Alan Turing", 39);
if (a == NULL || b == NULL) return 1;
printf("%s, %d\n", a->name, a->age);
printf("%s, %d\n", b->name, b->age);
person_free(a);
person_free(b);
return 0;
}Hedy Lamarr, 41
Alan Turing, 39
Pairing every "create" function with a matching "free" function, as with person_new / person_free, is a simple discipline that keeps ownership clear.
Summary
| Function | Purpose | Initialised? |
|---|---|---|
malloc(size) |
allocate size bytes |
no |
calloc(n, size) |
allocate n × size bytes |
yes, to zero |
realloc(p, size) |
resize a block, may move it | new part: no |
free(p) |
release a block | — |
Tip: Tools like Valgrind (
valgrind ./prog) or GCC's AddressSanitizer (gcc -fsanitize=address -g prog.c) detect leaks, use-after-free and out-of-bounds access. Use them whenever you work with the heap.
Go further: Use-After-Free (CWE-416) reads an AddressSanitizer report for a toy program and fixes the root cause.
Test yourself
What does malloc return when it cannot allocate the memory?
- 0 bytes of memory
- NULL
- -1
- It stops the program
What is the difference between malloc and calloc?
- calloc is faster
- calloc sets the memory to zero and takes a count and an element size
- malloc can only allocate ints
- There is no difference
What is a memory leak?
- Reading past the end of an array
- Allocated memory that is never freed
- Freeing memory twice
- Using too many local variables