We have also published about CppCheck which serves to perform static analysis.
In this article we are going to know and learn how to use Valgrind, which is a programming tool for memory debugging, memory leak detection and “profiling”.
Valgrind runs its code in a virtual machine, that is, nothing of the original program is executed directly in the processor! Instead, Valgrind first translates the program into a temporary, simpler form called an intermediate representation (IR), which is a form based on a processor-neutral static single assignment form.
Valgrind was originally designed to be a free memory debugging tool for x86 architectures, but has since evolved to become a generic framework for creating dynamic analysis tools such as checkers and profilers.
Valgrind is, in essence, a virtual machine that uses just-in-time compilation techniques, including dynamic recompilation.
Suppose you have the code below, which is a mini program that adds two numbers as parameters via the command line. The code uses Smart Pointers and everything is working normally!
Using Smart Pointers
After compiling, you run your code and decide to test it with Valgrind with the command and parameters:
Valgrind does not detect any failures and returns at the end of the output below: ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0), that is, no errors!
Allocating memory
Now you decide to modify your code and allocate memory with new declaration, but forget to deallocate with delete. Removed <memory> header and replaced make_shared in code below
Also, in addition to compiling without flags, you include all possible flags for error detection:
But still, no failure was detected.
Then, you can rerun Valgrind:
However, this time the detected error appears as listed in the output below:
Note that Memcheck, a Valgrind tool, detected that you forgot to deallocate the placeholder!
If your Valgrind shows an output error: Fatal error at startup I recommend you to install the libc6-dbg library, for example: