Stack vs. Heap Memory
When you run a program, the operating system assigns it some RAM. This memory is divided into two main areas: the Stack and the Heap.
The Stack (Ordered & Fast)
Think of a stack of plates. You can only add a plate to the top (Push), and you can only take a plate off the top (Pop). This is LIFO (Last In, First Out).
- What goes here? Local variables, function parameters, and return addresses.
- Speed: Extremely fast. The CPU just moves a pointer up or down.
- Limit: Small size (usually a few MB). If you exceed it (infinite recursion), you get a Stack Overflow.
- Automatic: Memory is freed immediately when a function finishes.
The Heap (Chaotic & Large)
Think of a giant laundry pile. You can throw clothes anywhere, and pull them out from anywhere.
- What goes here? Objects, Global variables, large data structures.
- Speed: Slower. The computer has to search for an empty spot to fit the data.
- Limit: Limited only by physical RAM (Gigabytes).
- Manual/GC: In languages like C++, you must delete this memory manually. In JavaScript/Python, a Garbage Collector scans the heap to clean up unused data, which causes performance pauses.
Summary
If you declare int x = 10;, it goes on the Stack.
If you declare User u = new User();, the pointer u is on the Stack, but the actual User object data is on the Heap.