Module 6 · Pointers and Memory — topic 4 of 5
Dynamic Memory Allocation
malloc, calloc and realloc request memory from the heap at run time, and free returns it. Learn to size allocations, check for failure, grow arrays, and avoid leaks and double frees.
Learning objectives
- Allocate arrays of run-time size with malloc and calloc
- Grow a buffer safely with realloc
- Free memory exactly once and avoid leaks
Definition
Dynamic memory allocation obtains storage with allocated storage duration from the heap at run time usingmalloc,callocorrealloc(declared in<stdlib.h>); the storage persists until it is explicitly released withfree.
Introduction
Fixed-size arrays force you to guess the maximum size when you write the program. Dynamic allocation lets you ask for exactly as much memory as you need when the program runs — for example after reading how many students there are.
Heap memory doesn't disappear when a function returns, so it can be returned to callers and used to build data structures that grow. In exchange, you must give it back with free when you are finished.
Why it matters
Linked lists, dynamic arrays, trees, hash tables and file buffers all rely on dynamic allocation. It is essential for every intermediate and advanced project in this course.
Memory leaks and use-after-free bugs are among the most serious defects in C software; learning disciplined allocation habits now prevents them.
Detailed explanation
`malloc(size)` returns a pointer to size bytes of uninitialised memory, or NULL on failure. Compute the size as count * sizeof *ptr so it stays correct if the type changes.
`calloc(count, size)` allocates count * size bytes and sets them all to zero. It also checks the multiplication for overflow.
`realloc(ptr, new_size)` resizes a block, possibly moving it. It returns the new address (and frees the old block) or NULL, in which case the original block is still valid. Always assign the result to a temporary first.
`free(ptr)` releases a block. Freeing NULL is a no-op. Freeing the same block twice, freeing memory not from malloc, or using memory after freeing it are undefined behaviour.
In C, void * converts implicitly to other object pointers, so casting malloc's result is unnecessary (it is required only in C++).
Syntax
sizeof *ais the size of one element, whatever its type.- Check every allocation for
NULL. - Set the pointer to
NULLafterfreeto avoid accidental reuse.
Code examples
An array sized at run time
6
1 4 9 16 25 36
calloc zero-fills
0.0 0.0 3.5 0.0
More examples
A growable integer list with realloc
grew to capacity 2 grew to capacity 4 grew to capacity 8 10 20 30 40 50 size 5, capacity 8
Step-by-step explanation
realloc(NULL, n)behaves likemalloc(n), so the first push needs no special case.- Capacity doubles (2, 4, 8), so the number of reallocations grows only logarithmically — amortised O(1) per push.
- The result goes into
tmp; ifreallocfailed,l->datawould still hold the original block, preventing a leak. l->data[l->size++] = valuestores the value and then increments the size.- One
freeat the end releases the whole buffer; the pointer is then set toNULL.
Expected output
Running “A growable integer list with realloc” prints exactly:
Practical applications
- C++'s
std::vectorand Python'slistgrow with the same doubling strategy. - Web servers allocate a buffer per connection and free it when the connection closes.
- Databases allocate pages from the heap as tables grow.
Best practices
- Pair every allocation with exactly one
freeon every code path. - Use
sizeof *ptrin size calculations. - Run tests with AddressSanitizer or Valgrind to catch leaks and invalid accesses.
Common mistakes
Losing the block on realloc failure
Avoid
Prefer
If realloc returns NULL, assigning it directly overwrites the only pointer to the old block — a leak.
Wrong size calculation
Avoid
Prefer
malloc(n) gives n bytes, enough for only n/4 ints. Writing n ints overflows the block.
Use after free
Avoid
Prefer
After free the memory may be reused; reading it is undefined behaviour.
Important notes
malloc(0)may returnNULLor a unique pointer that must not be dereferenced; avoid relying on either.- The operating system reclaims a process's memory when it exits, but long-running programs (servers, games) must free memory they no longer need.
Key takeaways
mallocgives uninitialised memory;calloczero-fills; both may returnNULL.- Use a temporary with
realloc. - Free each block exactly once; never use it afterwards.
Try it yourself
- 1Read n names (each up to 30 characters) into a dynamically allocated array of strings and print them in reverse.
- 2Write
char *join(const char *a, const char *b)that returns a newly allocated concatenation; the caller frees it.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat does `malloc` return if it cannot allocate the requested memory?
- BeginnerWhat is the key difference between `malloc(n * sizeof(int))` and `calloc(n, sizeof(int))`?
- ModerateWhat is the problem? `int *p = malloc(10 * sizeof *p); free(p); p[0] = 5;`