Junior — Middle
How can a memory leak be detected in an application?
sobes.tech AI
Answer from AI
Memory leaks can be detected using the following methods:
- Monitoring memory usage: Track the application's memory consumption over time using system tools (e.g.,
top,htop, Task Manager). - Memory profiling: Use specialized profilers (e.g., Valgrind, VisualVM, Memory Profiler for Python) that show objects that are not released after use.
- Logging and analysis: Implement logs that record object creation and deletion to identify discrepancies.
Example for Python using tracemalloc:
import tracemalloc
tracemalloc.start()
# application code
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:10]:
print(stat)
This helps locate where memory is allocated but not freed.