Skip to content
CurriculumChapter 31 · Pointers & Memory
AdvancedHigh focus~16 min

malloc, free & Heap Lifetime

The stack is automatic and bounded. The heap is manual and flexible. malloc gives you memory at runtime; free is the promise you make to give it back.

In plain English

malloc borrows a box from the heap, and free returns it. Forget to return it and the pile grows.

01

Heap allocation with malloc

malloc(size) reserves at least size bytes and returns a pointer to the block, or NULL if allocation fails. The memory is uninitialized. Casting the result of malloc is unnecessary in C. Use sizeof *pointer so the allocation stays correct if the pointed-to type changes. Always check for NULL before using the block.

chapter-31.cC
int *numbers = malloc(10 * sizeof *numbers);
if (numbers == NULL) {
    fprintf(stderr, "out of memory\n");
    return 1;
}

for (int i = 0; i < 10; i++) {
    numbers[i] = i * i;
}
02

free and pointer lifetime

free(pointer) releases the block. Every successful allocation needs a matching free, and you must not use the pointer after freeing it. Set the pointer to NULL after free to reduce dangling-pointer risk. Ownership should be clear: one part of the program is responsible for releasing each allocation.

chapter-31.cC
free(numbers);
numbers = NULL;   /* avoid a dangling pointer */

Watch it happen

Step through the memory changes one instruction at a time.

step-by-step

Step 1 of 5

Allocate from the heap

malloc(16) returns a heap block. p stores the block address; the bytes are uninitialized.

stack0x7ffc1000
int *p0x602000
heap · 16 bytes0x602000
p[0]
??
p[1]
??
p[2]
??
p[3]
??

Key takeaways

  • malloc returns uninitialized memory or NULL.
  • Use sizeof *pointer to size the allocation.
  • free releases a block; do not use the pointer afterward.
  • Set pointers to NULL after free.

Common pitfalls

  • Forgetting to check malloc for NULL.
  • Using memory after free.
  • Losing the only pointer to a block and leaking it.

Key focus

  • Know the malloc/free lifecycle.
  • Expect questions on NULL checks and dangling pointers.

Quick check

0 / 2 answered

1. What does malloc return on failure?

2. What should you do immediately after free(p)?