The short answer
Yes. Valgrind works with C++ programs on Linux. It checks the compiled program rather than the source, so you don’t need a special C++ build. Adding -g, the same flag covered in how to compile a c program for gdb, makes its reports show line numbers.
Why it works with C++
Valgrind watches the memory calls a program makes, whatever language produced them. C++ new, delete, new[], and delete[] all go through allocation functions that Valgrind can see, so it tracks each block. By default it also demangles C++ names, so reports show readable function names instead of mangled symbols.
Valgrind works at the level of bytes and blocks, not objects. It reports the leaked memory, but not the logic that skipped a destructor or the design that caused the leak.
What Valgrind catches in C++ code
- Memory from
newthat never gets adelete - Mismatched releases, such as
deleteon memory fromnew[] - Reads and writes past the end of a heap block, such as an index past the end of a
std::vectorallocation - Use of memory after
delete - Branches that depend on uninitialized values
Example: a mismatched delete
// mismatch.cpp
#include <iostream>
int main() {
int* values = new int[4];
values[0] = 1;
std::cout << values[0] << '\n';
delete values; // should be delete[] values
return 0;
}
Build with debug information and run it under Valgrind:
g++ -g -O0 -o mismatch mismatch.cpp
valgrind ./mismatch
Valgrind reports this (abbreviated):
Mismatched free() / delete / delete []
at 0x...: operator delete(void*) ...
by 0x...: main (mismatch.cpp:8)
Address 0x... is 0 bytes inside a block of size 16 alloc'd
at 0x...: operator new[](unsigned long) ...
by 0x...: main (mismatch.cpp:5)
The report names both lines: the block was allocated with new[] on line 5 and released with delete on line 8. The fix is delete[] values;.
Platform and version notes
Valgrind is built for Linux and doesn’t run natively on Windows. On Windows, use WSL2 with a Linux distribution, or use Dr. Memory or Visual Studio’s tools instead. Support for newer compiler output and CPU features depends on the Valgrind version, so install a recent release.
What Valgrind doesn’t do well with C++
- It slows programs down, sometimes by a large factor, so use small test inputs.
- It doesn’t find data races. Helgrind and DRD, two other Valgrind tools, check threaded code.
- It checks only the code paths that run during your test.
- It can’t be combined with AddressSanitizer in the same build.
- It can’t find logic errors, such as a loop that computes the wrong answer.
Where it fits
Valgrind is one option among several. If it isn’t available to you, the question of what tools can I use to detect memory leaks has other answers, including AddressSanitizer. For setup steps and a full run, see how to use valgrind in c.