Junior — Middle
Can you explain the principle of garbage collection in memory management?
sobes.tech AI
Answer from AI
Garbage Collector (GC) in memory management automatically frees memory occupied by objects that are no longer used by the program. In Python, for example, reference counting and cyclic garbage collection are used.
Main principles:
- Reference counting: each object has a reference count. When the count reaches 0, the object is deleted.
- Cycle detection: objects referencing each other can form cycles that reference counting cannot remove. For this, there is a cyclic garbage collector that periodically searches for such cycles and frees them.
Example:
import gc
# Enable cyclic garbage collector
gc.enable()
# Force garbage collection
gc.collect()
Thus, the garbage collector helps prevent memory leaks and relieves the programmer from manual memory management.