These days, most people who use a garbage collector are doing so inside a managed environment (like the Java Virtual Machine or the .NET Common Language Runtime). These managed environments add an additional wrinkle: they constrain the ability to take pointers to things. In the CLR for example, there is a notion of a pointer (which you can use through the managed IntPtr
or the unmanaged unsafe
code block), but there are limited conditions where you're allowed to use them. In most cases, you have to "pin" the corresponding objects in memory so that the GC doesn't move them while you're working with their pointers.
Why does this matter? Because, as it turns out, a managed allocator that is allowed to update pointers and move objects around in memory can be much more efficient than a malloc
-style allocator. You can do cool things like generational garbage collection, which makes heap allocations as fast as stack allocations, you can profile the memory behavior of your application much more easily, and, oh yeah, you can also easily detect unreferenced objects and free them automatically.
So it's not only a matter of increased programmer productivity (although if you ask anyone who works in a managed language, they'll attest to the increased productivity it gives them), it's also a matter of enabling entirely new programming technologies.
Finally, garbage collection becomes truly necessary when working with functional programming languages (or programming in functional styles). In fact, the very first garbage collector was invented by McCarthy in 1959 as part of the development of the Lisp language. The reason is twofold: first, functional programming encourages immutable data structures, which are easier to collect, and second, in pure functional programming there is no allocation function; memory always gets allocated as "stack" (function locals) and then moves to a "heap" if it is captured by a closure. (This is a gross oversimplification but serves to illustrate the point.)
So... if you're programming in an imperative style, and you're "wise enough" to do the Right Thing will all your memory allocations, you don't need garbage collection. But if you want to change your programming style to take advantage of the newest advances in programming technology, you'll probably be interested in using a garbage collector.