Reputation: 5227
Let us think of a memory leak program, wherein a block of heap memory is not freed and the program terminates. If this was (say) a Java Program, the in-built garbage collector would have automatically deallocated this heap block before the program exits.
But even in C++, if the program exits, wouldn't the Kernel automatically de-allocate all space associated with the process. Also in the Java code, the kernel would have to de-allocate the space for the text part (code) of the process (even if the stack and heap parts are deallocated by the garbage collector). So is the overall advantage of using a garbage collector feature - just the increased savings in time required to deallocate the heap by the program itself rather than the kernel? (if there is any such savings)
EDIT: A primary doubt of mine that has come about looking at the responses - will the GC invoke itself automatically when memory usage reaches a limit? Because, if a GC is only invoked just before the program terminates, it is not going to be useful for long programs.
Upvotes: 0
Views: 183
Reputation: 43331
Let's say that program allocates some resource, uses it all time it is running, but doesn't release it properly before exit. When this program exits, kernel deallocates all program resources - it is OK.
Now consider situation when some function creates memory leak on every call, and this function is called 100 times in a second. After few minutes or hours this program crashes because there is no free memory.
The bad thing is that programmer who makes memory and resource leaks of type 1, usually makes a leaks of type 2, producing dirty and unstable code. Professional programmer writes perfect code with 0 resource and memory leaks. If garbage collector is available - it is OK. If not - manage resources yourself.
BTW, it is still possible to make a leaks with garbage collector - like well-known .NET event source-consumer leak. So, garbage collector is very useful, saves a lot of developer time, but in any case developer must carefully manage program resources.
Upvotes: 0
Reputation:
So no, GC isn't about saving time. It's about saving tons of memory, preventing long-running allocation-intense programs from hogging all available memory and eventually making everyone die from out of memory errors.
Upvotes: 1