In: Computer Science
1. How we end up creating garbage cells? Give example C++ code.
Answer : If an object is created in C++ but is not destroyed before it goes out of scope, then we end up creating something known as garbage cell. For example, we have a pointer pointing to a particular varibal,e however, that variable becomes out of scope, that pointer becomes eligible for Garbage cell.
Example :
{
char *ptr = NULL;
{
char c;
ptr = &c;
}
// Now c is out of scope, thus ptr becomes eligible for Garbage collection.
}
2. What does garbage collection do?
Answer : Garbage Collection is a type of automatic memory management. It tries to collect and reclaim that garbage which won't be used again in the program.
Ususally, we store a program in two ways: Stack or heap.
The dynamically allocated variables inside a program are stored in a heap. Which by default has unlimited acces means it never gets deleted. However, that would lead to filling of memory soon. Thus, there is something known as Garbage collection that does this task for you automatically. We don't have to manage manually the memory, GC does it for us automatically.
3. Advantage to use a reference counter in GC?
Answer : Using reference counter in GC has a lot of advantages like:
- Objects can be reclaimed as soon as they become eligible for garbage collection and that too in an incremental manner and without any delay.
- Reference counter is useful for realtime performance in GC. Thus, it gives a more consistent performance with no pauses,
4. two ways to avoid fragmentation in allocation of different sizes.:
- Compaction is the tchnique used to avoid fragmentation.
- Copying Garbage Collection : A copying garbage collector compacts the heap to eliminate unused space completely.
This way fragmentation can be avoided.
Hope it helps!
Please upvote if you like it!
Thank you:)