Skip to main content
Be Bitwise
CC Basics & Memory

malloc() and free()

malloc and free are the two pillars of dynamic memory in C. Between them, you get direct, hands-on control of the heap.

malloc: Allocating Memory

malloc (memory allocate) requests a block of memory from the heap:

c
#include <stdlib.h>
int *p = malloc(sizeof(int));

That call asks the heap for sizeof(int) bytes — usually four — and hands you back a pointer to the start of the block. If the request can't be satisfied, you get NULL instead.

Always check for NULL:

c
int *p = malloc(sizeof(int));
if (p == NULL) {
fprintf(stderr, "Out of memory!\n");
return 1;
}

free: Releasing Memory

Once you're finished with a heap block, hand it back:

c
free(p);

After free, that block goes back to the allocator's pool. The variable p still contains the same numeric address, but the bytes there are no longer yours. Touch them and you're trespassing.

Key Concept

A dangling pointer still aims at an address whose memory has already been freed. Dereferencing one is undefined behaviour: maybe a crash, maybe silent corruption, maybe everything looks fine until the day a customer hits the bug in production.

Common Patterns

Allocating an array:

c
int *arr = malloc(10 * sizeof(int));
for (int i = 0; i < 10; i++) {
arr[i] = i * i;
}
// ... use arr ...
free(arr);

calloc for zeroed memory:

c
int *arr = calloc(10, sizeof(int)); // all elements initialized to 0

realloc to resize:

c
int *bigger = realloc(arr, 20 * sizeof(int)); // grow to 20 elements
if (bigger == NULL) {
// arr is still valid and still yours to free
free(arr);
return 1;
}
arr = bigger;

Use a temporary. If realloc fails it returns NULL and leaves the old block untouched, so arr = realloc(arr, ...) would overwrite your only pointer to it and leak the lot.

Two more things malloc won't do for you: it doesn't zero the block (that's what calloc is for), and malloc(0) may return either NULL or a unique pointer you still have to free.

The Three Cardinal Sins

  1. Memory leak. You forget to free. Those bytes stay claimed until the process dies.
  2. Use after free. You touch a block after handing it back. Undefined behaviour, often the worst kind: the silent kind.
  3. Double free. You free the same pointer twice and watch the allocator's bookkeeping unravel.
c
// Memory leak
void leak() {
int *p = malloc(sizeof(int));
// oops, forgot to free
}
// Use after free
int *p = malloc(sizeof(int));
free(p);
*p = 42; // DANGER: undefined behavior
// Double free
int *p = malloc(sizeof(int));
free(p);
free(p); // DANGER: undefined behavior

Try It

Use the editor below to practise. Allocate an int on the heap, store 42 in it, print it, and free it.

Then hunt a leak. The program below wraps malloc and free with a counter so it can report how many blocks are still alive at exit. One of make_greeting's error paths forgets to clean up after itself. Find it and fix it so the last line reads 0.

Try itLeaks love early returns. Fix the function, not main.
C (GCC 9.2.0)
Show the answer

The empty-name check returns without freeing copy. Add free(copy); before that return NULL;, or move the check above the first malloc so there's nothing to clean up.

Challenges

Allocate an integer on the heap, set it to 42, print it, then free the memory.

C (GCC 9.2.0)