Valgrind is a collection of tools that will help us to make our C program faster and to a great extend error free. The most common of these tools is called Memcheck. Mecmcheck can detect memory related errors.
One of the most hard to find bug in C is memory leak. Memory leak errors can be easily detected using the Memcheck.
The program must be compiled using the option ‘-g’ in order to get the exact line number in which error occurred. Optimization option like ‘-o1’ can lead to unexpected behavior. Thus try to avoid the optimization options. Memcheck will issue messages about memory errors and leaks whenever it detects one.
Let’s find out the memory error and leak in the following piece of code.
In the above code there are two problems:
- x = 0 : we have only allocated a memory block of size 40 bytes. x is outside that block.
- The allocated block in never freed leading to memory leak.
We can see both these error using Memcheck. The name of the file used above is valgrind.c. The usage of Memcheck is as follows:
In order to include the exact line number in the error message add ‘-g’ option while compiling.
Now run the binary ‘a.out’:
On running the code a detailed error report of the above mentioned two errors is displayed.
The common sequence, ==17822==, is the process id. The first line give the reason for error. In this case the reason for error is writing in a memory location not allocated for it. The rest of the lines give the stack trace expressing each steps before the error occurred.
The heap summary gives the information about the memory leak when the program exit.
The heap summery tells that at the time of exit 40 bytes were in use.
The memory leak details is shown in leak summary.
The leak summary points out that the 40 bytes allocated as a single block is now not recoverable in the program.
Valgrind works like a virtual machine. It runs the code by its own and examine each step and report the memory error and leak. This will be time consuming for large programs. We cannot depend fully on valgrind for a perfect solution if we are expert. But as a beginner or little above that valgrind is a perfect tool. If we are able to come close to no errors in valgrind, the code is almost like a perfect one.