Sometimes you cannot know the size you need until the program runs — the heap exists for exactly that.
1 Sizes unknown up front
When the amount of data depends on user input, fixed-size arrays are not enough.
2 malloc asks the heap
malloc(n) reserves n bytes while the program runs and hands back the address.
3 free gives it back
Every malloc must be matched by exactly one free — otherwise the memory leaks.
4 Check for NULL
If the request fails, malloc returns NULL — test the pointer before using it.
Memory sized at runtime
Sizes unknown up front1When the amount of data depends on user input, fixed-size arrays are not enough. malloc asks the heap2malloc(n) reserves n bytes while the program runs and hands back the address. free gives it back3Every malloc must be matched by exactly one free — otherwise the memory leaks. Check for NULL4If the request fails, malloc returns NULL — test the pointer before using it. 4 building blocks make up Memory sized at runtime
malloc hands you a block of cells on the heap. Drag to orbit, then play the script to fill and free it.
Drag to orbit the scene. Press Play to watch memory in action.
Press play — reserve the block, fill it with a loop, print, then give it back.
preprocessThe preprocessor pastes in stdio.h and stdlib.h — malloc and free live in stdlib.h.
Memory
no variables yet — press play
Console
output appears as the program runs…
Four moves, always in this order: ask, check, use, free.
process decision input / output start / end A heap block, a sum, a free — what gets printed?
Your predicted output — one line per console line
Hint: The sum is computed while the block is alive — freeing first would leave nums dangling.
01malloc(n) returns the address of n bytes on the heap — or NULL if it fails.
02Every malloc needs exactly one free, or the memory leaks.
03After free, the pointer dangles — never read or write through it again.
04calloc(n, size) also zeroes the memory; malloc leaves it uninitialized.
05Check for NULL before using the block — always.