Definition - What does Garbage Collector mean?
A garbage collector is a piece of software that performs automatic memory management. Its job is to free any unused memory and ensure that no memory is freed while it is still in use. Some languages such as Java and .NET languages feature automatic garbage collection, whereas others such as C/C++ require the programmer to manual manage memory.
Techopedia explains Garbage Collector
Garbage collection was first introduced by Lisp creator John McCarthy to ease the manual memory management when working with the Lisp language.
The three main techniques used by a garbage collector to perform automatic memory management are as follows:
- Reference counting -- The reference to each object is counted using a counter variable. When the counter reaches zero, it denotes that the object is no longer needed and thus is recycled.
- Mark and sweep -- A recursive traversal of all reachable objects is carried out on all data regions, and reachable objects are marked. The unmarked objects are then recycled.
- Stop and copy -- The memory heap is divided into two sections: a section that contains the objects and an empty section where the objects are transferred (copied) if found to be marked. The unmarked objects in the first section are recycled by emptying it.
When a block of memory assigned to a pointer/object has been freed, the pointer/object must be reset to a null value; otherwise, it is dangling, i.e., pointing to an invalid memory block.
Garbage collection helps reduce bugs and security risks caused by dangling pointers and memory leak problems.
The disadvantages of using a garbage collector include the extra overhead on resources and performance. Running a garbage collector may also slow down the system and thus decrease its performance.