Introduction
Objects created in heap memory require garbage collection. Basically, there are two way to do automatic garbage collection.
This kind of garbage collector uses reference counting i.e whenever a object is created, we also keep a count of number of pointers referring to that object called the reference count. Then, if the reference count become zero i.e. we have no pointer pointing to that object, then it releases the memory. A good example of this is the shared/unique/weak pointers in C++ STL
This kind of garbage collector periodically perform garbage collection i.e. after some interval a garbage collector runs and any not referenced memory objects are freed. A good example is Java. Basically, it starts from a set of base objects (say all objects in the stack), follows the references and mark any object we encounter on the way as ok. Then it sweeps the entire heap again and any object found not marked is unreachable and therefore are freed.
Reference
http://www.careercup.com/question?id=5097145818415104