I was reading the C# entry on Wikipedia, and came across:
Managed memory cannot be explicitly freed; instead, it is automatically garbage collected.
Why is it that in languages with automatic memory management, manual management isn’t even allowed? I can see that in most cases it wouldn’t be necessary, but wouldn’t it come in handy where you are tight on memory and don’t want to rely on the GC being smart?
Garbage collection enforces the type safety of a memory allocator by guaranteeing that memory allocations never alias. That is, if a piece of memory is currently being viewed as a type
T, the memory allocator can guarantee (with garbage collection) that while that reference is alive, it will always refer to aT. More specifically, it means that the memory allocator will never return that memory as a different type.Now, if a memory allocator allows for manual
free()and uses garbage collection, it must ensure that the memory youfree()‘d is not referenced by anyone else; in other words, that the reference you pass in tofree()is the only reference to that memory. Most of the time this is prohibitively expensive to do given an arbitrary call tofree(), so most memory allocators that use garbage collection do not allow for it.That isn’t to say it is not possible; if you could express a single-referrent type, you could manage it manually. But at that point it would be easier to either stop using a GC language or simply not worry about it.