Why Your Code Crashes (Stack vs Heap)

LearnThatStack · Beginner ·⚡ Algorithms & Data Structures ·6mo ago

Key Takeaways

Understanding memory management using the stack and heap

Full Transcript

You create a list, pass it to a function, and somehow it changed. You never touched it, but it changed. Or this a recursive function that runs fine at first until it crashes. Stack overflow. Or your app's memory keeps growing. You're using garbage collection. It should clean up, but it doesn't. These aren't random. They're all caused by the same misunderstanding. How memory actually works. Today, let's understand this better. Your program's memory is divided into two regions. One is small, fast, and automatic, the stack. The other is large, flexible, and requires management, the heap. Let's start with the stack because it's where your function calls live. So, how does the stack work? Think of your editor's undo history. Every action goes on top. Undo removes the most recent, always the top, never the middle. This is last in, first out. The stack works exactly the same way. Each function call gets pushed on top. So when we call main, a stack frame is created. It holds everything main needs, local variables and where to return when done. When main calls greet, a new frame is pushed on top. This frame holds the parameters and local variables. Each function gets its own isolated workspace. When greet returns, its frame is popped off instantly. No cleanup code, no garbage collector, just move a pointer. This is why the stack is fast. But speed requires constraints, fixed size, typically 1 to 8 megabytes depending on your system. Data dies when the function returns and allocation sizes must be known in advance. Violate these constraints and your program crashes. Two reasons to overflow. Reason one, runaway recursion. Each call adds a frame. No stopping condition means infinite frames frame after frame until you hit the ceiling. Stack overflow. Reason two, oversized local variables. This array is 4 MGB on systems with a 1 megabyte stack limit like the default on some operating systems. This crashes instantly. Same error, different causes. One is depth, too many frames. The other is size, a frame too large. Fix for recursion. always have a base case fix for large data. Put it on the heap instead. So where does large data live? Where do objects survive after a function returns? The heap. The heap is a large pool of memory. It can grow to use most of your available RAM. Unlike the stack's neat ordering, heap allocations are scattered. You request space. The system finds a free block and gives you its address. You use the heap when you don't know how much space you need until runtime when data needs to survive after the function returns or when it's too large for the stack. But if heap data lives somewhere in this large pool, how do you access it? Through a reference, an address that tells you where the data lives. The reference is tiny, just a few bytes. It lives on the stack. The data it points to lives on the heap. When you write my list equals a list, the variable doesn't contain the list. It contains the address of the list. This is the mental model you need. Your variable holds an address. The data is elsewhere. And this explains one of the most common reasons for confusion. What happens when you pass data to a function depends on what you're passing. Thinking with primitives, numbers, booleans, the value is copied. The function gets its own independent copy. This is passed by value. Changes inside don't affect the original. With objects, the reference is copied. Now two references point to the same heap data. Modify through one, you see it through the other. This is why your list changed. You passed its address, not the data. Primitives, separate copies, objects, shared data. This distinction prevents countless debugging sessions. Garbage collected languages can absolutely leak memory. Here's how. The collector starts from your stack references and traces every reference chain. Anything reachable is kept. Anything unreachable is deleted. The collector traces from the roots. Reachable objects survive. Unreachable objects are collected. Automatic. But what if you keep references to objects you no longer need? This cache grows forever. Every stored object is reachable through the cache. The garbage collector sees active references. It can't help you. This is a memory leak. Objects you're done with but forgot to release. The fix is explicit cleanup. Remove references when done. Use structures like weak map that don't prevent collection. Set size limits. The garbage collector handles unreachable memory. Making memory unreachable is your job. This should be your mental model. The stack fast, small, automatic, holds function frames, primitives, and references. Data dies with the function. The heap, flexible, large, managed, holds objects and dynamic data, lives until nothing references it. Stack overflow, you exceeded the limit. Memory leak, you held references too long. Unexpected mutation, you shared heap data, not mysteries, logical consequences. Next time you hit a memory error, is it a stack problem or a heap problem? Stack means depth or size. Heap means references or lifetimes. Hopefully this helped you understand memory better. If you found this valuable, please like and share and don't forget to subscribe for more explanations. Thanks for watching. See you in the next one.

Original Description

Ever passed a list to a function and it changed without you touching it? That's not a bug — that's how memory works. In this video, I break down the two regions of memory: the stack and the heap. You'll learn why stack overflows happen, how memory leaks occur even with garbage collection, and why your data sometimes mutates unexpectedly. This isn't abstract theory — these are the concepts that explain real bugs you've probably encountered. What you'll learn: - How the stack works - Why stack overflows happen - What the heap - Pass by value vs pass by reference - Memory leaks in garbage-collected languages Timestamps: 0:00 - The mystery: your data changed 0:28 - Chapter 1: The Stack 1:45 - Stack Overflow — Both Causes 2:24 - Chapter 2: The Heap 3:27 - Pass by Value vs Reference 4:04 - Memory Leaks (even with GC) 4:56 - Recap & Mental Model 5:24 - Actionable Takeaway More Videos : Software Egineering Basics - https://www.youtube.com/playlist?list=PLWP-VtjCVpWyLNBm3zz_sGyC5mVwiAOvj Software Design - https://www.youtube.com/playlist?list=PLWP-VtjCVpWx7kPq30XRN6O6LjVQ4VL95 #programming #coding #developer #computerscience #memory #tutorial
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Related Reads

Chapters (8)

The mystery: your data changed
0:28 Chapter 1: The Stack
1:45 Stack Overflow — Both Causes
2:24 Chapter 2: The Heap
3:27 Pass by Value vs Reference
4:04 Memory Leaks (even with GC)
4:56 Recap & Mental Model
5:24 Actionable Takeaway
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →