Using Valgrind

Sukhbeer Dhillon
2 min readDec 5, 2019

Almost grinding my teeth

You’ve recently made a program with pointers and all C/C++ cool tings. And now, just because, you want to see if you have a memory leak problem. The most basic command to use is as follows:

valgrind --leak-check=yes ./a.out 
valgrind --leak-check=yes --log-file="valgrind" -v ./a.out

If you’re too fancy and want to get verbose details, do this:

valgrind --leak-check=full  \
--show-leak-kinds=all \
--track-origins=yes \
--verbose \
--log-file=valgrind-out.txt \
./a.out

Remember to prepare your executable (a.out in my case) with the debug option ( -g if using gcc).

Here are the main information blocks that I saw with my programs:

This message tells that I did not free the memory that I allocated. Valgrind tells me that the byte blocks are lost. If you see this, clearly understand that your destructor isn’t doing what its supposed to.

There is also this:

This message pops up when your program is trying to read an address which is pointing to null. Basically that means, your pointing is pointing to null, but you’re either trying to read what could potentially be stored at that address. In the above, you can see that valgrind tells you where the memory for this pointed to object was allocated at in the Block was alloc'd at line. Then you can also see where it was free'd . And finally the place where I was trying to read this released memory ( Line 460 of table.h ).

Invalid free means that you’re trying to delete something that was already deleted. This is again a common error in destructors or move/copy operations. To avoid this, check what you need to remove.

There is one last one that I had in my code, but since I fixed it and did not save the overwrote the original valgrind-out file, I dont have a sample of that one. The error usually reads likeMismatched free() / delete / delete [].

This happens when you allocated using new() and tried to deallocate with delete[] or vice-versa, where you allocated with new[] and deallocated with delete object. Read more here.

--

--