Dynamic memory: malloc & free
The heap gives you memory that outlives the frame that asked for it — and never cleans up after you.
Before you start
Local variables die when their function returns. That is a problem if you want a value to outlive its function — say, a linked list you keep adding to, or an image loaded once and shown many times.
The **heap** is a separate area of memory where you ask for space explicitly (malloc) and give it back explicitly (free). Space you take from the heap survives until *you* release it, no matter which function is running.
The freedom comes with a bill: if you forget to free, you leak memory. If you free twice, or use the memory after freeing it, you get corruption. This lesson walks through both the happy path and the classic bugs.
Stack
Heap
lives until you free it — not until the function returns`nums` lives on the stack. What it will point to will not.
Step 1 of 9. Two regions, two lifetimes. Stack memory is tied to a frame: it appears on call and vanishes on return, automatically. Heap memory is tied to nothing. It appears when you ask, and stays until you say otherwise — even after the function that created it has returned. That is the whole reason to use it.
Step 01 / 09
Two regions, two lifetimes
Stack memory is tied to a frame: it appears on call and vanishes on return, automatically.
Heap memory is tied to nothing. It appears when you ask, and stays until you say otherwise — even after the function that created it has returned. That is the whole reason to use it.
#include <stdio.h>#include <stdlib.h>int main(void) { int *nums = malloc(4 * sizeof(int)); if (nums == NULL) return 1; nums[0] = 7; nums[1] = 9; free(nums); nums = NULL; return 0;}