Dynamic Memory Allocation

Lesson 15 of 20

Ask the heap for memory at runtime with malloc, fill it, and hand it back with free — leaks not included.

The big picture

Memory sized at runtime

Sometimes you cannot know the size you need until the program runs — the heap exists for exactly that.

Sizes unknown up front

When the amount of data depends on user input, fixed-size arrays are not enough.

malloc asks the heap

malloc(n) reserves n bytes while the program runs and hands back the address.

free gives it back

Every malloc must be matched by exactly one free — otherwise the memory leaks.

Check for NULL

If the request fails, malloc returns NULL — test the pointer before using it.