Topic 7 of 15 · Intermediate
Dynamic Memory: malloc & free
Heap allocation with malloc, calloc, realloc and free.
Concept
Stack memory is automatic and freed when a function returns. Heap memory is requested at run time and lives until you free it.
malloc(bytes) returns uninitialised memory; calloc(n, size) zeroes it; realloc resizes a block. All return NULL on failure.
Every malloc needs exactly one free. Forgetting causes leaks; freeing twice or using after free is undefined behaviour. Tools like Valgrind find these bugs.
Cheat sheet
| Function | Does |
|---|---|
| malloc(n) | n bytes, uninitialised |
| calloc(k, n) | k×n bytes, zeroed |
| realloc(p, n) | Resize, may move |
| free(p) | Release memory |
Code (C17)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5;
int *arr = malloc(n * sizeof *arr);
if (!arr) return 1;
for (int i = 0; i < n; i++) arr[i] = i * i;
int *bigger = realloc(arr, 10 * sizeof *arr);
if (!bigger) { free(arr); return 1; }
arr = bigger;
free(arr);
arr = NULL;
return 0;
}Remember
- Check the return value of malloc.
- Assign realloc to a temp pointer first.
- free + set to NULL.
Interview questions
malloc vs calloc?
malloc takes total bytes and leaves memory uninitialised; calloc takes count and size and zero-fills.
What is a memory leak?
Heap memory that is never freed after it's no longer reachable, so the program's memory use keeps growing.
Lesson test
Take an 8-question test on “Dynamic Memory: malloc & free” — concepts, output prediction, bug spotting and interview questions.