Valgrind and Memory Leaks

How to Use Valgrind With C++

Learn how to install Valgrind, build a C++ program for it, run Memcheck, and read leak and memory error reports, with examples you can try yourself.

On this page
  1. What Valgrind does
  2. Install Valgrind
  3. Build with debug information
  4. Run your first check
  5. Read the leak report
  6. Memory errors: reads and writes outside a block
  7. Use after free
  8. Mismatched allocation and free
  9. Uninitialized values
  10. Fix the bugs with standard C++ tools
  11. Useful options
  12. Limits to keep in mind
  13. Where to go next

What Valgrind does

Valgrind runs your program and checks every memory access it makes. Its default tool, Memcheck, reports problems that a C++ compiler usually can’t catch at build time:

  • Memory that is allocated but never freed (a leak)
  • Reads or writes outside the bounds of an allocated block
  • Use of memory after it has been freed
  • Values that are used before they are set

You don’t need to change your source code. Valgrind does make programs run much slower, often many times slower, so use it during development and testing rather than in production. It runs on Linux, including Linux under WSL2 on Windows. Whether it fits your setup is covered in does valgrind work for c++.

Install Valgrind

On Debian and Ubuntu, install it with:

sudo apt install valgrind

On Fedora, use sudo dnf install valgrind. On Arch Linux, use sudo pacman -S valgrind. To confirm the install, run:

valgrind --version

Build with debug information

Valgrind shows line numbers only when the program includes debug information. Compile with -g to add it, and use -O0 to turn off optimization so the reported lines match your source:

g++ -g -O0 -Wall -Wextra -o leak leak.cpp

Optimized builds can reorder or remove code, which makes reports harder to read. Keep the debug build for Valgrind and use an optimized build for timing tests. Clang accepts the same flags, so you can swap g++ for clang++. GDB needs the same flags, and how to compile a c program for gdb covers them in more detail.

Run your first check

This small program leaks memory. It allocates an array and never frees it:

// leak.cpp
#include <iostream>

int main() {
    int* numbers = new int[5];  // allocated, never freed
    numbers[0] = 42;
    std::cout << numbers[0] << '\n';
    return 0;
}

Run it under Valgrind with --leak-check=full, which lists each leak with the line that caused it:

valgrind --leak-check=full ./leak

The full report is long, so here is the part that matters, abbreviated. Valgrind prefixes each line with a process ID, and addresses change from run to run:

20 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x...: operator new[](unsigned long) ...
   by 0x...: main (leak.cpp:5)

LEAK SUMMARY:
   definitely lost: 20 bytes in 1 blocks

Five ints at 4 bytes each come to 20 bytes on most systems. The by line points to line 5 of leak.cpp, where the allocation happens.

Read the leak report

Valgrind sorts leaks into kinds, and each kind says how serious the leak is:

  • Definitely lost: no pointer to the memory remains. This is a real leak, so fix it.
  • Indirectly lost: the block can be reached only through another lost block. Fix the first leak in the chain and these go away.
  • Possibly lost: a pointer may point into the block, but Valgrind can’t be certain. Check the code before deciding.
  • Still reachable: a pointer still exists when the program exits. Global and static objects often show up here, so this is less serious than definitely lost.

By default Valgrind reports only definitely and possibly lost blocks. Add --show-leak-kinds=all to see every kind.

Memory errors: reads and writes outside a block

Writing past the end of an array is undefined behavior. Sometimes it crashes at once. Often the program seems to work, which makes the bug hard to find. Valgrind catches it either way:

// overflow.cpp
#include <iostream>

int main() {
    int* values = new int[3];
    values[3] = 7;  // valid indexes are 0, 1, and 2
    std::cout << values[0] << '\n';
    delete[] values;
    return 0;
}

Valgrind’s report, abbreviated, looks like this:

Invalid write of size 4
   at 0x...: main (overflow.cpp:6)
 Address 0x... is 0 bytes after a block of size 12 alloc'd
   at 0x...: operator new[](unsigned long) ...
   by 0x...: main (overflow.cpp:5)

The bad write is on line 6: one int past the end of a block of three int values, which is 12 bytes. Bugs like this can end in a crash, and what is segmentation fault in c explains that crash if it is new to you.

Use after free

Reading or writing memory after delete is also undefined behavior:

// use_after_free.cpp
#include <iostream>

int main() {
    int* score = new int(90);
    delete score;
    std::cout << *score << '\n';  // reads memory that was already freed
    return 0;
}

Valgrind reports (abbreviated):

Invalid read of size 4
   at 0x...: main (use_after_free.cpp:7)
 Address 0x... is 0 bytes inside a block of size 4 free'd
   at 0x...: operator delete(void*) ...
   by 0x...: main (use_after_free.cpp:6)

The report shows where the bad read happens and where the block was freed. To fix it, don’t touch the pointer after delete. Better, let std::unique_ptr own the object, so there is no manual delete to get wrong:

#include <iostream>
#include <memory>

int main() {
    auto score = std::make_unique<int>(90);
    std::cout << *score << '\n';
    return 0;
}

Mismatched allocation and free

Each allocation needs the matching release. Memory from new goes back with delete, memory from new[] goes back with delete[], and memory from malloc goes back with free. Mixing them is undefined behavior. If you call delete on an array made with new[], Valgrind reports:

Mismatched free() / delete / delete []

Fix it by matching the release to the allocation. For an array, that means delete[].

Uninitialized values

If your program reads a variable before setting it, Valgrind reports:

Conditional jump or move depends on uninitialised value(s)

This appears when the value affects an if, a loop condition, or another branch. The fix is to initialize the variable where you declare it, such as int total = 0;. Add --track-origins=yes to see where the uninitialized value was created. It makes the run slower, so turn it on only when you need the extra detail.

Fix the bugs with standard C++ tools

Many of these bugs can’t happen when the standard library owns the memory:

  • std::vector replaces new[] and delete[]. It frees its memory when it goes out of scope.
  • std::unique_ptr, made with std::make_unique, owns a single object.
  • .at() checks the index on a vector and throws std::out_of_range for a bad index. [] does not check it.
// leak_fixed.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers(5);  // freed automatically when main returns
    numbers[0] = 42;
    std::cout << numbers[0] << '\n';
    return 0;
}

Useful options

Combine these flags as needed:

valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --error-exitcode=1 ./leak
  • --leak-check=full lists each leak with its stack trace.
  • --show-leak-kinds=all includes still reachable blocks and every other kind.
  • --track-origins=yes traces uninitialized values back to where they were created.
  • --error-exitcode=1 makes Valgrind exit with status 1 when it finds errors, which is useful in test scripts.
  • --log-file=valgrind.log writes the report to a file instead of the terminal.
  • --suppressions=file.supp hides known noise from libraries you don’t control.

Limits to keep in mind

  • Valgrind checks only the code that actually runs. A bug on an untested path stays hidden.
  • It doesn’t find data races. Helgrind and DRD, two other Valgrind tools, check threaded code.
  • It doesn’t run natively on Windows.
  • It slows programs down a lot, so test with small inputs.
  • Don’t use it together with AddressSanitizer in the same build.

Where to go next

Valgrind is one answer to the question of what tools can I use to detect memory leaks. Sanitizers are another common choice. Run your checker on every test build, and fix the first error it reports before the rest, because one early error often causes the ones after it.

Keep exploring

Guides from other topics

All topics →