Introduction to Memory Leaks
Fundamentals on Computing for Robotics, Graphics and Computer Vision
Darío Suárez - Adolfo Muñoz
Introduction to Memory Leaks and how to fix them
Goals
- Understand why memory leaks occur
- Learn how tofind and fix memory leaks
- use memory leak detection tools
Introduction
- A memory leak is a heap-allocated unreachable memory location
- Consequences: resource depletion and memory leaks
- In large programs, hard to detect
- For large enough executions and notable leaks, after a long time
the operating system can kill an application that would
return out of memory error
- Note: This topic does not cover buffer overflow issues
Memory leak example
void leak() {
int *ptr = new int[10]; // C++
}
Valgrind
- Open source tool for memory leaks detection
- Broadly, an instrumentation framework for building dynamic analysis tools
- Other usages: profiling or concurrency issues …
- Supported in platforms such as: AMD64, AARCH64, …
- More information available at https://valgrind.org>
Using Valgrind
- Compile with
-g and 0 or 1 optimization level, -O[01]
- Higher optimization levels may generate inexisting uninitialised-value errors
- Run your application within valgrind environment:
valgrind --leak-check=yes app <list of args>
Valgrind's output
- The output can be large, so you could preserve it on a file; e.g,
valgrind --leak-check=yes app <list of args> 2>1 | tee output.txt | less
- Memory leaks looks as:
==19182== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==19182== at 0x1B8FF5CD: malloc (vg_replace_malloc.c:130)
==19182== by 0x8048385: f (a.c:5)
==19182== by 0x80483AB: main (a.c:11)
Suggested workflow
- With the least of memory leaks from valgrind try to remove them all
- When working with external libraries, being leakage free may be impossible
Quiz
- Can Valgrind detect this error?
Summary
- Remeber to use smart pointers
- Test your code with memory-issues tools
- Explore tools such linters as well