Table of Contents

IronForgeCyber

Courses

Resources

Blog

Log In



IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. c-programming
  3. memory
8 min read

Dynamic Memory

Every variable we have written so far has had its size fixed in the source code: int x, or int arr[4]. But very often you do not know how much memory you need until the program is already running — you are reading a file whose length you cannot predict, or building a list that grows as input arrives. For that, you ask the system for memory at runtime. That memory comes from the heap, and managing it yourself is one of the defining skills of writing C.

The Stack vs the Heap

Your program's data lives in a few different regions of memory. Two of them hold the variables you create, and they behave very differently:

  • The stack is automatic. Every local variable you declare lives here, and the compiler manages it for you — space appears when a function is called and vanishes when it returns. It is fast and effortless, but its sizes are fixed at compile time, and anything on it disappears the moment its function returns. We cover it in detail in The Stack.
  • The heap is manual. It is a large pool of memory you can request blocks from while the program runs, in whatever size you decide, and those blocks stay alive until you hand them back. The freedom costs you responsibility: nothing is cleaned up automatically.

The short version: use the stack for ordinary local variables, and reach for the heap when you need memory whose size or lifetime the stack cannot give you.

malloc, calloc, realloc

You request heap memory with malloc (memory allocate). You tell it how many bytes you want, and it returns a pointer to a block of that size — or NULL if the request could not be satisfied. Because it can fail, you check the result before using it:

c
1int *arr = malloc(10 * sizeof(int));
2if (arr == NULL)

Notice the sizeof(int) — you ask for bytes, so you multiply the number of elements by the size of each one. The block malloc hands back is called a chunk: a contiguous run of bytes at some address on the heap, yours to use until you free it. Its contents start as garbage — whatever was left there before — so do not read from it until you have written something.

If you want that memory zeroed for you, use calloc instead. It takes the count and element size as two arguments and clears every byte to 0, which is exactly what you want for a fresh array:

c
int *arr = calloc(10, sizeof(int)); // 10 ints, every one set to 0

And when a chunk turns out to be the wrong size, realloc resizes it — growing or shrinking — and returns a pointer to the result. It may move the chunk elsewhere to find room, so you always reassign the pointer it gives back:

c
arr = realloc(arr, 20 * sizeof(int)); // same data, now room for 20 ints

free and Ownership

Heap memory is not cleaned up for you. Every chunk you take with malloc (or calloc, or realloc) must be handed back with exactly one call to free:

c
1free(arr);
2arr = NULL; // the pointer is now dangling — null it so you can't misuse it

After free, the chunk no longer belongs to you, and the pointer that referred to it is a dangling pointer — using it is a bug. Setting it to NULL is a cheap habit that turns a silent mistake into an obvious one.

This is where the idea of ownership comes in. For every chunk, exactly one part of your code should be responsible for freeing it. "Who owns this pointer, and whose job is it to free it?" is a question you will ask constantly in C, because the language will not answer it for you.

Freed chunks do not go to waste — the heap keeps them and hands them back out. Watch what happens when we free a chunk and immediately allocate another of the same size:

1. malloc a, b, c a b c free 2. free(b); malloc → d a d c free reused

We can watch the heap do exactly this. The program below allocates a chunk, prints its address, frees it, then allocates another of the same size and prints that address too:

reuse.c
1#include <stdio.h>
2#include <stdlib.h>
3
4int main(void)
$ gcc reuse.c -o reuse$ ./reusefirst:  0x564648d0c2a0second: 0x564648d0c2a0

The two addresses are identical. Freeing a returned its chunk to the heap, and the very next request for the same size handed that exact block straight back as b. This reuse is why the heap stays efficient, and also why a pointer to freed memory is so dangerous — the chunk it points at may already belong to something else.

Common Leaks and Double-Frees

Two mistakes dominate heap bugs, and both come from breaking the one-malloc-one-free rule.

A memory leak is forgetting to free. The chunk stays reserved even though nothing points to it anymore, so your program's memory footprint only grows. A leak in a short-lived program is harmless — the operating system reclaims everything on exit — but in anything long-running it is a slow death. Leaks are easy to miss by eye, which is why we use tools like valgrind to find them, covered in Debugging.

A double-free is calling free twice on the same chunk. The heap tracks which chunks are free using bookkeeping stored right alongside your data, and freeing twice corrupts it. Modern C libraries detect many cases and stop the program rather than let the corruption spread:

doublefree.c
1#include <stdlib.h>
2
3int main(void)
4{
5    int
gdb
$ gcc doublefree.c -o doublefreegef➤ runfree(): double free detected in tcache 2Program received signal SIGABRT, Aborted.

The library noticed the second free, printed double free detected, and aborted with SIGABRT — the program killing itself on purpose because continuing would be worse. A use-after-free, writing through a pointer whose chunk you already freed, is the same family of bug and is often invisible until something far away breaks.

The rules that avoid all of this are short:

  • One free for every malloc, no more and no fewer.
  • Set a pointer to NULL right after you free it.
  • Never read or write through a pointer once its chunk is freed.

That is the heap at an introductory level — enough to allocate, resize, and release memory safely. Underneath, the heap is a rich data structure of its own, with arenas, bins, and chunk headers that become their own playground once you reach heap exploitation; that is a whole course in its own right. For now, next we turn to the other half of the picture — The Stack, where your local variables and function calls actually live.

3{
4 // the allocation failed — handle it, don't use arr
5 return 1;
6}
5
{
6 int *a = malloc(sizeof(int));
7 printf("first: %p\n", (void *) a);
8 free(a);
9
10 int *b = malloc(sizeof(int));
11 printf("second: %p\n", (void *) b);
12 return 0;
13}
*
p
=
malloc
(
sizeof
(
int
)
)
;
6 free(p);
7 free(p); // the same chunk, freed a second time
8 return 0;
9}