Lesson 22: Dynamic memory — stack, heap & malloc
So far all our variables lived on the stack: they are created automatically, their size is fixed in advance, and they disappear when the function ends. Sometimes that's not enough — for example when you want an array whose size is known only at runtime. That's what the heap is for: you request memor
The stack is like a cafeteria tray: you get it automatically and it's taken away at the end of the meal without asking. The heap is like a storage-rental facility: you ask for a unit of whatever size you choose (malloc), get a key (the pointer), and the unit is yours — until you return the key (free). Lose the key without returning it, and the unit stays occupied.
- stack
- Automatic memory area: local variables live here and disappear when the function ends. Their size must be fixed in advance.
- heap
- Memory area you request blocks from at runtime. What you asked for, you are responsible for releasing with free.
- malloc(size)
- Requests a block of size bytes from the heap and returns its address, or NULL on failure. Requires #include <stdlib.h>.
- free(p)
- Returns the block p points to back to the heap. Every malloc needs one free when you're done.
- NULL check
- Right after malloc, check if (p == NULL) — when there isn't enough free memory, malloc returns NULL and the pointer must not be used.