How do the stack and the heap work?
Stack
A per-thread memory region with automatic LIFO allocation: on a function call its frame (locals, return address) is pushed on top, on return it is popped. Allocation is just moving the stack pointer.
- very fast, no synchronization — every thread has its own stack;
- the frame size is known at compile time;
- limited: 1 MB for the main thread on iOS, 512 KB for background
Thread/GCD threads by default; deep recursion → stack overflow; - lifetime is strictly tied to scope.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep