Development (General)

How garbage collection works: mark and sweep explained

How garbage collection frees memory your code no longer uses: reachability, mark and sweep, reference counting, and why C and C++ make you free memory by hand.

  • 6 min read
  • 5 questions
  • +35 XP
Transcript

Garbage Collection, explained by cats. Kitty writes code. Her program creates lots of objects. Fish, bowls, toys, boxes. Over time, some objects aren’t used anymore. Old fish. Broken toys. Empty bowls. They just sit there, taking up memory. If Kitty doesn’t clean up, the memory fills up.

The app slows down. Or crashes. No tuna for anyone. So the Garbage Collector steps in. A cat that prowls through memory, sniffs out unused objects, and cleans them up. Deletes what’s no longer needed. Frees space for new things.

In languages like Java, C#, and Python, this cat works automatically. Always cleaning behind the scenes. But in C or C++, Kitty must clean by paw. Manually free every object she created. One mistake and memory leak. Garbage collector keeps memory tidy. Code runs smooth. And Kitty’s bowl never overflows