Skip to content

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.

Beginner 18 min read·Lesson 25 of 37 in C Programming

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 using malloc, calloc or realloc (declared in <stdlib.h>); the storage persists until it is explicitly released with free.

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++).

Stack (automatic)Heap (dynamic)
Allocated byentering a blockmalloc/calloc/realloc
Freed byleaving the blockfree
Sizefixed at compile time (or VLA)chosen at run time
Typical limit1–8 MBmost of RAM
Speedvery fastslower (allocator)

Syntax

C
#include <stdlib.h>
int *a = malloc(n * sizeof *a); /* uninitialised */
int *z = calloc(n, sizeof *z); /* zero-filled */
if (a == NULL) { /* handle failure */ }
int *tmp = realloc(a, 2 * n * sizeof *a);
if (tmp) a = tmp; /* only replace on success */
free(a);
a = NULL;
  • sizeof *a is the size of one element, whatever its type.
  • Check every allocation for NULL.
  • Set the pointer to NULL after free to avoid accidental reuse.

Code examples

An array sized at run time

C
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
if (scanf("%d", &n) != 1 || n <= 0) return 1;
int *sq = malloc(n * sizeof *sq);
if (!sq) return 1;
for (int i = 0; i < n; i++) sq[i] = (i + 1) * (i + 1);
for (int i = 0; i < n; i++) printf("%d ", sq[i]);
printf("\n");
free(sq);
return 0;
}
Input
6
Output
1 4 9 16 25 36

calloc zero-fills

C
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double *v = calloc(4, sizeof *v);
if (!v) return 1;
v[2] = 3.5;
for (int i = 0; i < 4; i++) printf("%.1f ", v[i]);
printf("\n");
free(v);
return 0;
}
Output
0.0 0.0 3.5 0.0

More examples

A growable integer list with realloc

C
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
size_t size, capacity;
} IntList;
int push(IntList *l, int value) {
if (l->size == l->capacity) {
size_t cap = l->capacity ? l->capacity * 2 : 2;
int *tmp = realloc(l->data, cap * sizeof *tmp);
if (!tmp) return 0; /* old data still valid */
l->data = tmp;
l->capacity = cap;
printf("grew to capacity %zu\n", cap);
}
l->data[l->size++] = value;
return 1;
}
int main(void) {
IntList list = {NULL, 0, 0};
for (int i = 1; i <= 5; i++)
if (!push(&list, i * 10)) { free(list.data); return 1; }
for (size_t i = 0; i < list.size; i++) printf("%d ", list.data[i]);
printf("\nsize %zu, capacity %zu\n", list.size, list.capacity);
free(list.data);
list.data = NULL;
return 0;
}
Output
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 like malloc(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; if realloc failed, l->data would still hold the original block, preventing a leak.
  • l->data[l->size++] = value stores the value and then increments the size.
  • One free at the end releases the whole buffer; the pointer is then set to NULL.

Expected output

Running “A growable integer list with realloc” prints exactly:

TextOutput
grew to capacity 2
grew to capacity 4
grew to capacity 8
10 20 30 40 50
size 5, capacity 8

Practical applications

  • C++'s std::vector and Python's list grow 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 free on every code path.
  • Use sizeof *ptr in size calculations.
  • Run tests with AddressSanitizer or Valgrind to catch leaks and invalid accesses.

Common mistakes

Losing the block on realloc failure

Avoid

p = realloc(p, bigger);

Prefer

int *tmp = realloc(p, bigger);
if (tmp) p = tmp;
else { /* p still valid: free or keep it */ }

If realloc returns NULL, assigning it directly overwrites the only pointer to the old block — a leak.

Wrong size calculation

Avoid

int *a = malloc(n);

Prefer

int *a = malloc(n * sizeof *a);

malloc(n) gives n bytes, enough for only n/4 ints. Writing n ints overflows the block.

Use after free

Avoid

free(p);
printf("%d\n", *p);

Prefer

printf("%d\n", *p);
free(p);
p = NULL;

After free the memory may be reused; reading it is undefined behaviour.

Important notes

  • malloc(0) may return NULL or 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

  • malloc gives uninitialised memory; calloc zero-fills; both may return NULL.
  • Use a temporary with realloc.
  • Free each block exactly once; never use it afterwards.

Try it yourself

  1. 1
    Read n names (each up to 30 characters) into a dynamically allocated array of strings and print them in reverse.
  2. 2
    Write 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;`
Practise this topic