Stack and Heap
Every running C program has two very different places to put data: the stack and the heap. Understanding the difference is essential once your programs get bigger than a single function.
The stack
Local variables live on the stack, memory is claimed automatically when a function is called and freed automatically the instant it returns:
The stack is extremely fast (allocating is just moving a pointer), but limited in size (usually a few MB) and strictly scoped, you can never return a pointer to a local stack variable and use it after the function returns, that memory is gone.
The heap
The heap is a much larger pool of memory that you manage manually, with malloc and free:
Heap memory survives until you explicitly free it, which is exactly what makes it useful for data that needs to outlive the function that created it, and exactly what makes it dangerous: forget to free and you leak memory, free twice or use it after freeing and you get undefined behavior.
| Stack | Heap | |
|---|---|---|
| Managed by | The compiler, automatically | You, manually (malloc/free) |
| Speed | Very fast | Slower |
| Size | Small, fixed | Large, limited by system RAM |
| Lifetime | Ends when function returns | Until you free it |
WARNING
Forgetting to free heap memory is a memory leak. This is exactly the problem garbage collectors exist to solve, and exactly what you'll build one for later in this course.