Dynamic memory is requested from the heap at run time with malloc, calloc and realloc and returned with free. It sizes data to the input, but every block must be checked and freed exactly once — leaks, dangling pointers and double frees are classic bugs.
Automatic memory is like seats booked when the timetable is printed: fixed in number and released automatically. The heap is a hotel where you ask for rooms on arrival — malloc books a room, calloc books rooms already cleaned (zeroed), realloc moves you to a bigger room (possibly in another wing), and free checks you out. Forget to check out and the room stays taken for ever — a memory leak; return after checking out and someone else may be in it — a dangling pointer.
Key points — the night-before list
Stack memory (locals) is automatic and limited; heap memory is requested and released by the programmer and lasts until free.
void *malloc(size_t bytes) returns an uninitialised block, or NULL on failure. Idiom: int *p = malloc(n * sizeof *p);
calloc(n, size) allocates n × size bytes and sets them all to zero; note its two arguments.
realloc(p, new_size) may move the block (contents preserved); assign the result to a temporary so that a NULL return does not lose the old block.
free(p) returns the block but leaves p dangling — set p = NULL. free(NULL) is harmless; freeing twice is undefined.
A memory leak is an allocated block with no pointer left to it; long-running programs then slowly run out of memory.
All four functions are declared in <stdlib.h>. In C the void * result needs no cast; C++ needs one (but should use new/delete).
valgrind (Memcheck) and AddressSanitizer (-fsanitize=address) catch leaks, invalid reads/writes, use after free and double free.
01Static versus dynamic allocation; stack versus heap
With static (compile-time) allocation, sizes are fixed when the program is written: int marks[100]; reserves 100 ints whether the class has 12 students or 200. Dynamic (run-time) allocation requests exactly the memory needed once the size is known — read n, then ask for n ints — and gives it back when finished. Pointers make this possible: the allocator hands back an address, and the program reaches the memory through a pointer. (A KPSC question: dynamic allocation is achieved with pointers, and the binding happens at run time.)
TextTypical memory layout of a running C program
high addresses
+------------------------+
| stack | frames of active calls; grows DOWN
| | |
| v |
| |
| ^ |
| | |
| heap | malloc / calloc / realloc; grows UP
+------------------------+
| BSS (zero-filled) | uninitialised globals and statics
| initialised data | globals and statics with initial values
| text (code) | machine instructions, read-only
+------------------------+
low addresses
Stack
Holds auto locals, parameters and return addresses
Allocated and released automatically on call and return (LIFO)
Very fast — just move the stack pointer
Small: often 8 MB on Linux, 1 MB on Windows; overflowing it crashes
Object sizes fixed at compile time (VLAs aside)
Heap
Holds blocks obtained from malloc, calloc and realloc
Released only by an explicit free, or at program exit
Slower — the allocator must find and track blocks
Large: limited by the available (virtual) memory
Sizes chosen at run time; blocks can grow with realloc; can fragment
Function
Purpose
Initial contents
Returns
malloc(size)
allocate one block of size bytes
indeterminate (garbage)
pointer to the block, or NULL
calloc(n, size)
allocate n elements of size bytes each
all bits zero
pointer, or NULL
realloc(p, size)
resize the block at p, moving it if necessary
old contents kept; any extra part indeterminate
pointer to the (possibly new) block, or NULL
free(p)
release a block obtained from the above
—
nothing (void)
The four functions, all declared in <stdlib.h>
02malloc: allocating a block
void *malloc(size_t size); reserves a contiguous block of size bytes on the heap and returns its address as a void *, which C converts automatically to any object pointer type. The block's contents are indeterminate — whatever bytes happened to be there. If the request cannot be satisfied, malloc returns NULL, so every call must be checked before the memory is used.
CA dynamic one-dimensional array
#include <stdio.h>#include <stdlib.h>
int main(void)
{
int n = 5;
int *a = malloc(n * sizeof *a); /* n ints: 20 bytes with 4-byte int */
if (a == NULL) { /* ALWAYS check */
fprintf(stderr, "out of memory\n");
return 1;
}
for (int i = 0; i < n; i++)
a[i] = i * i; /* use it exactly like an array */
for (int i = 0; i < n; i++)
printf("%d ", a[i]); /* 0 1 4 9 16 */
printf("\n");
free(a); /* give the block back */
a = NULL; /* and forget its address */
return 0;
}
Write malloc(n * sizeof *p) rather than malloc(n * 4): it stays correct on every machine and even if the type of p changes later.
The cast (int *)malloc(…) is optional in C, because void * converts implicitly, and required in C++. Many C programmers leave it out, since in C89 it could hide a missing #include <stdlib.h>.
malloc(0) may return NULL or a unique pointer that must not be dereferenced — implementation-defined.
sizeof a for the pointer above is 8 on a 64-bit system (the size of the pointer), not 20 — the program must remember n itself.
Allocators usually keep hidden bookkeeping beside each block, so writing even one byte past the end can corrupt the heap.
C++ note (asked in KPSC papers)
C++ still supports malloc and free, but its new operator also runs constructors, returns a correctly typed pointer and throws std::bad_alloc on failure, while delete runs destructors. Never mix the two families: free what malloc gave, delete what new gave.
void *calloc(size_t n, size_t size); allocates memory for n elements of size bytes each — n × size bytes in all — and sets every bit to zero, so an int array starts as all 0s. It takes two arguments, and good implementations also detect when n × size would overflow. It is the answer to the classic question 'which function allocates multiple blocks of the same size?'
Ccalloc, then growing the block safely with realloc
#include <stdio.h>#include <stdlib.h>
int main(void)
{
int *p = calloc(5, sizeof *p); /* 5 ints, all zero */
if (p == NULL) return 1;
p[2] = 7;
int *tmp = realloc(p, 10 * sizeof *p); /* grow to 10 ints */
if (tmp == NULL) { /* failed: p is still valid */
free(p);
return 1;
}
p = tmp; /* success: use the new address */
for (int i = 5; i < 10; i++)
p[i] = -1; /* the new part is NOT zeroed */
printf("%d %d %d\n", p[0], p[2], p[9]); /* 0 7 -1 */
free(p);
return 0;
}
void *realloc(void *p, size_t new_size); changes the size of the block at p. If the block can grow in place, it does. Otherwise realloc allocates a new block, copies the old contents (up to the smaller of the two sizes), frees the old block and returns the new address — so after a successful realloc, any other pointer into the old block is dangling. On failure it returns NULL and leaves the old block untouched. realloc(NULL, n) behaves like malloc(n); avoid realloc(p, 0), whose behaviour varies between systems (C23 makes it undefined).
The classic realloc leak
p = realloc(p, bigger); overwrites p with NULL when the call fails, losing the only pointer to the old block. Always assign to a temporary, check it, and only then assign it back — exactly as in the code above.
Grow by doubling: capacity 1 → 2 → 4 → 8 → … → 2ᵏ
element copies while inserting n items ≤ 1 + 2 + 4 + … + n/2 < n
⇒ amortised O(1) work per insertion
Grow by a fixed +10 each time:
copies ≈ 10 + 20 + 30 + … + n ≈ n²/20 ⇒ O(n) per insertion on average
Why growing arrays double their capacity
04free, and the bugs around it
void free(void *p); returns a block to the allocator so it can be reused. It must receive exactly a pointer that malloc, calloc or realloc returned, and each block must be freed once. free cannot change your variable, so afterwards p still holds the old address — it is now a dangling pointer. Setting p = NULL; straight after free makes a later mistake fail loudly instead of silently, and free(NULL) is defined to do nothing.
Bug
Example
Consequence
Memory leak
p = malloc(40); p = malloc(80); — the first block is now unreachable
memory is never returned; long-running programs grow until they fail
Dangling pointer / use after free
free(p); p[0] = 1;
undefined: may corrupt data that a later allocation now uses
Double free
free(p); free(p);
undefined: usually heap corruption or an abort
Freeing non-heap memory
int a[10]; free(a);
undefined behaviour
Freeing a pointer into the middle
free(p + 1);
undefined: free needs the exact start of the block
Heap buffer overflow
p = malloc(10); p[10] = 0;
corrupts neighbouring blocks or the allocator's own data
Missing NULL check
p = malloc(huge); *p = 1;
a NULL dereference when memory runs out
The heap bug catalogue
CTwo ways to leak memory
#include <stdlib.h>#include <string.h>
char *copy_or_null(const char *s)
{
char *out = malloc(strlen(s) + 1);
if (out == NULL) return NULL;
if (s[0] == '\0')
return NULL; /* LEAK: out was allocated but never freed */
strcpy(out, s);
return out; /* the CALLER now owns out and must free it */
}
void leaky_loop(void)
{
for (int i = 0; i < 1000; i++) {
int *tmp = malloc(100 * sizeof *tmp);
if (tmp == NULL) return;
tmp[0] = i;
/* missing free(tmp): 1000 blocks (about 400 KB) lost on every call */
}
}
The cure is a clear ownership rule: for every allocation, decide which function is responsible for freeing it, document that, and free on every path — including early returns and error exits. Functions that return newly allocated memory (such as copy_or_null above, or POSIX strdup) hand ownership to their caller.
KPSC (Lecturer IT) pattern
A function mallocs a buffer when s > 0 but returns NULL when s == 1 without freeing it. The question 'this is an example of …?' expects memory leak — the allocated block is lost on that path.
05Dynamic one- and two-dimensional arrays
A dynamic 1-D array is simply T *p = malloc(n * sizeof *p);, used as p[i]. For a 2-D array whose rows and columns are known only at run time, three layouts are common; they differ in how many allocations they make, whether the data is contiguous, and how they are freed.
CThree ways to build a rows × cols matrix at run time
#include <stdio.h>#include <stdlib.h>
int main(void)
{
int rows = 3, cols = 4;
/* Method 1: array of row pointers - rows + 1 allocations; rows may differ */
int **m = malloc(rows * sizeof *m);
if (m == NULL) return 1;
for (int i = 0; i < rows; i++) {
m[i] = malloc(cols * sizeof *m[i]);
if (m[i] == NULL) return 1; /* real code would free what it got */
}
m[2][3] = 11;
/* Method 2: one contiguous block, indexed by hand */
int *flat = malloc(rows * cols * sizeof *flat);
if (flat == NULL) return 1;
flat[2 * cols + 3] = 11; /* element [2][3] *//* Method 3: pointer to a row (C99 VLA type) - one block, real [i][j] */
int (*grid)[cols] = malloc(rows * sizeof *grid);
if (grid == NULL) return 1;
grid[2][3] = 11;
printf("%d %d %d\n", m[2][3], flat[2 * cols + 3], grid[2][3]); /* 11 11 11 */
for (int i = 0; i < rows; i++) /* free rows first, then the table */
free(m[i]);
free(m);
free(flat);
free(grid);
return 0;
}
Layout
malloc calls
Bytes requested
Freed with
Array of row pointers (int **)
rows + 1 = 4
3 × 8 for pointers + 48 for data = 72
free each row, then the pointer array
Single flat block (int *)
1
48
one free
Pointer to rows (int (*)[cols])
1
48
one free
Comparing the layouts for a 3 × 4 int matrix on a 64-bit system
Which layout when?
Method 1 is what char **argv and 'jagged' arrays (rows of different lengths) look like. Methods 2 and 3 keep all the data contiguous, which is faster and needs only one free.
06Building a linked list with malloc
Dynamic memory plus self-referential structures gives linked lists: each node is a separately allocated struct node holding data and a pointer to the next node, so the list grows and shrinks one node at a time without moving any other data. Try the same operations in the Linked-list visualiser on this page.
CInsert at the front, append at the end, and free the whole list
#include <stdio.h>#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *push_front(struct node *head, int value)
{
struct node *n = malloc(sizeof *n);
if (n == NULL) { perror("malloc"); exit(EXIT_FAILURE); }
n->data = value;
n->next = head; /* the new node points to the old first node */
return n; /* and becomes the new head */
}
void append(struct node **head, int value) /* pointer to the head pointer */
{
struct node *n = malloc(sizeof *n);
if (n == NULL) { perror("malloc"); exit(EXIT_FAILURE); }
n->data = value;
n->next = NULL;
while (*head != NULL) /* walk to the last next field */
head = &(*head)->next;
*head = n;
}
void free_list(struct node *head)
{
while (head != NULL) {
struct node *next = head->next; /* save it BEFORE freeing */
free(head);
head = next;
}
}
int main(void)
{
struct node *list = NULL;
list = push_front(list, 10);
list = push_front(list, 20);
append(&list, 30); /* 20 -> 10 -> 30 */
for (struct node *p = list; p != NULL; p = p->next)
printf("%d -> ", p->data);
printf("NULL\n"); /* 20 -> 10 -> 30 -> NULL */
free_list(list);
list = NULL;
return 0;
}
Two details matter. append takes a pointer to the head pointer, so it can change the caller's head when the list is empty — the same idea as passing a pointer's address to a function that allocates. And free_list copies head->nextbefore calling free, because reading a field of a node after freeing it is a use-after-free.
The tempting but wrong free loop
for (p = head; p != NULL; p = p->next) free(p); looks neat, but after free(p) the update expression reads p->next from freed memory. It may even appear to work — until the allocator reuses the block. Save the next pointer first, as free_list does.
07Growing data at run time, and fragmentation
Many programs cannot know in advance how much data will arrive. The standard answer is a growable (dynamic) array: keep a pointer, the number of elements in use (size) and the number allocated (capacity); when size reaches capacity, realloc to double the capacity. This is how C++'s std::vector and Java's ArrayList work inside.
CA growable int array built on realloc
#include <stdio.h>#include <stdlib.h>
struct intvec {
int *data;
size_t size; /* elements in use */
size_t cap; /* elements allocated */
};
int push(struct intvec *v, int value)
{
if (v->size == v->cap) { /* full: grow */
size_t newcap = v->cap ? 2 * v->cap : 1; /* 1, 2, 4, 8, ... */
int *tmp = realloc(v->data, newcap * sizeof *tmp);
if (tmp == NULL) return 0; /* old data still valid */
v->data = tmp;
v->cap = newcap;
}
v->data[v->size++] = value;
return 1;
}
int main(void)
{
struct intvec v = {NULL, 0, 0}; /* realloc(NULL, n) behaves like malloc(n) */
for (int i = 1; i <= 10; i++)
if (!push(&v, i * i)) { free(v.data); return 1; }
printf("size %zu, capacity %zu, last %d\n", v.size, v.cap, v.data[v.size - 1]);
/* size 10, capacity 16, last 100 */
free(v.data);
return 0;
}
Heap memory can also be wasted without any leak. External fragmentation occurs when free memory is split into many small, scattered holes, so a large request fails even though the total free space would be enough. Internal fragmentation is space wasted inside allocated blocks, because allocators round each request up (for example to a multiple of 16 bytes) and add a hidden header. Allocators choose holes with strategies such as first fit, best fit and worst fit — the same ideas met in operating-system memory management.
No garbage collector
C never reclaims heap memory automatically: a block is released only by free, or by the operating system when the whole program ends. Languages such as Java, Python and C# use a garbage collector that frees unreachable objects for you — convenient, but with run-time overhead that C avoids.
08Finding memory bugs: valgrind and friends
Memory bugs rarely crash where they happen, so tools are essential. Valgrind's default tool, Memcheck (mainly used on Linux), runs the program on a simulated CPU and reports every invalid read or write, every use of an uninitialised value, double frees and — when the program exits — every block that is still allocated.
Bourne shellChecking a program that leaks one 40-byte block (addresses and line numbers will differ)
$ gcc -g -O0 leak.c -o leak # leak.c: p = malloc(40); p = malloc(80); free(p);
$ valgrind --leak-check=full ./leak
==1234== HEAP SUMMARY:
==1234== in use at exit: 40 bytes in 1 blocks
==1234== total heap usage: 2 allocs, 1 frees, 120 bytes allocated
==1234==
==1234== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==1234== at 0x4848899: malloc (vg_replace_malloc.c:381)
==1234== by 0x109162: main (leak.c:5)
AddressSanitizer: compile with gcc -fsanitize=address -g (GCC or Clang). It is much faster than valgrind and stops at the first heap overflow, use after free or double free with a precise report; its LeakSanitizer component lists leaks at exit on Linux.
Valgrind's leak categories: definitely lost (no pointer to the block remains — a real leak), indirectly lost (reachable only through a lost block), possibly lost, and still reachable (pointers still exist at exit).
Habits that prevent most bugs: check every allocation; pair every malloc with exactly one free on every path; set pointers to NULL after free; write sizeof *p; never return pointers to locals; give each block one clear owner.
Quick facts
malloc, calloc, realloc and free live in <stdlib.h>; dynamic memory comes from the heap; malloc leaves memory uninitialised while calloc zeroes it; all three allocators return NULL on failure; and a block survives until it is freed or the program ends — not merely until the function that allocated it returns.
Step through · The life of one heap block
step 1 / 9
Step 1: malloc(40)
The program asks the C library's allocator for 40 bytes. The allocator first searches its free list for a free block that is large enough.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Memory accounting with malloc, calloc and realloc
With 4-byte ints: int *a = malloc(10 * sizeof(int)); int *b = calloc(10, sizeof(int)); int *t = realloc(a, 20 * sizeof(int)); if (t) a = t; How many bytes does each call request, what do b[0..9], a[0..9] and a[10..19] contain, and how much memory is allocated at the end?
EX 2Spot the leak (KPSC Lecturer IT style)
What kind of error does this function contain? char *foo(int s) { char *output; if (s > 0) output = (char *)malloc(size); if (s == 1) return NULL; return output; }
EX 3The realloc trap
Explain what goes wrong with buf = realloc(buf, 2 * cap); when memory runs out, and write the safe version.
EX 4Heap usage of a linked list
On a 64-bit system, three nodes of struct node { int data; struct node *next; } are created with malloc by pushing 10, 20 and 30 at the front. Give the final list, the heap bytes requested and the number of free calls needed.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Write a program that reads n, allocates an array of n floats, reads the values, prints their average and frees the memory. Handle allocation failure.
Q2
Predict the output: int *p = calloc(5, sizeof(int)); p[2] = 7; int *t = realloc(p, 10 * sizeof(int)); if (t) p = t; printf("%d %d", p[2], p[0]);
Q3
Name the bug in each fragment: (a) free(p); free(p); (b) int *p = malloc(4); p = malloc(8); (c) int a[10]; free(a); (d) free(p); p[0] = 1; (e) int *p = malloc(10); p[3] = 0; with 4-byte ints.
Q4
A 3 × 4 int matrix is allocated as an array of row pointers on a 64-bit system. How many malloc calls and free calls are needed, and how many bytes are requested? Compare with one contiguous allocation.
Q5
This function should free a whole list. What is wrong, and how do you fix it? void free_all(struct node *head) { for (struct node *p = head; p != NULL; p = p->next) free(p); }
Exam traps
malloc does not zero memory; calloc does. calloc takes two arguments (count, size), malloc one (total bytes).
p = realloc(p, n); leaks the old block if realloc fails and returns NULL — use a temporary pointer.
free(p) does not set p to NULL, so p is left dangling. free(NULL) is harmless, but freeing the same block twice is undefined.
Free only what malloc/calloc/realloc returned, using the exact pointer — never a stack array, never p + 1.
sizeof(p) for a malloc'd array is the pointer size (8 on 64-bit), not the block size — keep track of the length yourself.
Heap memory is not released when the allocating function returns, only by free or at program exit. Casting malloc's result is optional in C but required in C++.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.