Image for Mark-and-Sweep

Mark-and-Sweep

Mark-and-Sweep is a method used by programming languages to manage memory automatically. It works in two phases: First, it "marks" all objects that are still in use by starting from roots like variables or functions and tracing the objects they reference. Second, it "sweeps" through the entire memory, removing (freeing) any objects that weren't marked, as they are no longer needed. This process helps prevent memory leaks by ensuring only active objects occupy memory, keeping programs efficient without requiring manual cleanup.