Memory
Allocation
Every variable, array, and object lives somewhere in RAM. Knowing whether that place is the stack or heap — and who is responsible for freeing it — prevents crashes, leaks, and undefined behaviour.
How is memory allocated for data structures?
Programs use two main memory areas. The stack holds function call frames and small fixed-size values, and is fast and automatically freed. The heap holds objects whose size and lifetime vary, such as arrays and objects. In JavaScript, objects live on the heap and the garbage collector frees them once nothing references them.
Stack
- • Fixed size (usually 1–8 MB)
- • LIFO — push on call, pop on return
- • Extremely fast O(1) alloc/free
- • Limited to scope of the function
- • Overflow → StackOverflowError
Heap
- • Large — limited only by available RAM
- • Random access, unordered
- • Slower allocation (OS syscall)
- • Data survives function returns
- • Must free — or GC handles it
Stack allocation
1// Stack memory — automatic, LIFO allocation2function doWork():3 x = 42 // allocated on stack frame4 arr = [1,2,3] // small arrays: stack5 return x // frame popped on return, memory freed6// x no longer accessible — stack frame gone
Heap allocation
1// Heap memory — manual / GC managed2function makeList(n):3 node = new ListNode(n) // heap allocation4 node.next = new ListNode(n - 1)5 return node // heap data survives return67// In GC languages: freed when no references remain8// In C/C++: must call free() / delete — or leak!
The allocation lifecycle
Stack allocation
The runtime pushes a new stack frame when a function is called. Local variables live inside this frame. When the function returns, the frame is popped — memory is freed instantly at O(1) cost.
Memory map
Process memory layout: stack grows down from high addresses, heap grows up from low addresses.
🎯 Quick Check
Which of these statements about stack memory is correct?
Memory Allocation: summary
Key points
- Arrays are stored in contiguous memory, which makes index access O(1) and cache-friendly.
- Linked structures scatter nodes across the heap and connect them with references (pointers).
- Garbage collection frees unreachable objects, but references you forget to drop (leaks) keep memory alive.
- A stack overflow happens when recursion goes too deep for the call stack.
Frequently asked questions
›What is the difference between stack and heap memory?
The stack is small, fast and automatically managed per function call. The heap is large and flexible, holds objects and arrays, and is cleaned up by the garbage collector in JavaScript.
›Why are arrays faster than linked lists?
Array elements sit next to each other in memory, so the CPU cache loads several at once. Linked list nodes are scattered, so each step can be a cache miss.