Algorithm

Memory Model: Stack vs Heap

Language Basics & Mechanics Pattern

Memory Model: Stack vs Heap

Understand how primitive values and reference objects are stored in memory, how pointer/reference assignments work, and how function calls push frames onto the Stack.

CONSTRAINTS
  • Stack memory: LIFO order, fast allocation, fixed size per thread
  • Heap memory: Dynamic allocation, reference pointer storage, Garbage Collected (Java/Py/JS) or Manual (C++)
EXAMPLE 1
Input: a = [1, 2, 3]; b = a; b[0] = 99
Output: a is now [99, 2, 3]
b and a point to the exact same array object on the Heap.
Why does Python or JavaScript pass objects by reference?
To avoid copying large arrays/objects in memory on every function call. Copying a reference pointer is O(1) time.

Understanding where your variables live in RAM is essential for writing bug-free data structures.

Stack vs Heap Breakdown

- The Call Stack: Stores function execution frames, primitive values (int, double, bool), and object reference pointers.
- The Heap: Stores dynamic data objects, arrays, trees, and linked list nodes.

Pass-by-Value vs Pass-by-Reference

- When passing a primitive to a function, a copy is pushed to the stack frame.
- When passing an Object/Array, a copy of the reference pointer is passed. Mutating array elements inside the function alters the object on the Heap!

Interactive Strategy Visualization
🚧

Simulation Under Construction

This algorithm visualization is currently being built by our engineering team. We are ensuring it meets our high-fidelity standards for multi-language parity.

High FidelityMulti-LanguageInteractive
Memory model mechanics: Stack vs Heap.