I have read this-
Memory that is allocated by malloc(for example) and that is not freed
using free() function is released when the program terminates.And
that it is done by the opearting system. So when does having or not
having a garbage collector come into picture?
Or is it that not all operating systems do this automatic release of memory on program termination?
That claim about
mallocandfreeis correct for all modern computing operating systems. But the statement as a whole reflects a complete misunderstanding of the purpose of garbage collection.The reason you call
freeis not to clean things up for after your program terminates. The reason you callfreeis to permit the memory to be re-used during the subsequent execution of a long-running program.Consider a message server that handles a hundred messages per second. You call
mallocwhen you receive a new message. And then you have to do lots of things with it. You may have to log it. You may have to send it to other clients. You may have to write it to a database. When you are done, if you don’tfreeit, after a few days you’ll have millions of messages stuck in memory. So you have to callfree.But when do you call
free? When one client is done sending a message, another client might still be using it. And maybe the database still needs it.The purpose of garbage collection is to ensure that object’s used memory is released (so it can be re-used to hold a new message during the application’s lifetime) without having to burden the application programmer with the duty (and risks) associated with tracking exactly when the object is no longer required by any code that might be using it.
If an application doesn’t run for very long or doesn’t have any objects whose lifetimes are difficult to figure out, then garbage collection doesn’t do very much good. And there are other techniques (such as reference-counted pointers) that can provide many of the same benefits as garbage collection. But there is a real problem that garbage collection does solve.