Using Valgrind to check memory
How to use Valgrind
-To valgrind the program, run the valgrind command and give it our program name as an argument.
-For example, if we want to run ./myProgram hello 42, we can simply run Valgrind ./myProgram hello 42.
Uninitialized Values
-When we run the program, we may use uninitialized values. It needs to be fixed. Valgrind can tell us about the use of uninitialized values. But it only tell when the control flow of the program depends on the unitialized value. For example, uninitialized value appears in the conditional expression of an if, or a loop, or in the switch statement.
-If we want to know where the uninitialized value is from, we can use Valgrind --track-origins=yes ./myProgram
-Using -fsanitize=address can find a lot of problems that Memcheck cannot.
-We can use Valgrind with GDB to debug. We can run:
--vgdb=full --vgdb-error=0., then Valgrind will stop on the first error that it encounters and give control to GDB.
Dynamic Allocation Issues
-Memcheck will explicitly track which addresses are valid and which are not. It also tracks exactly what pointers were returned by malloc, new and new[].
-Valgrind can detect is an access goes past the end of a dynamically allocated array.
-It can also detect double freeing pointers, freeing the incorrect pointer, and mismatches between allocations and deallocations. It also checks for memory leaks.
-We can use:
Valgrind --leak-check=full option to check full information about memory leak.
memorycheck.h
-We can use the header file Valgrind, for example, memorycheck.h to interact with Valgrind's tolls directly.
VALGRIND_CHECK_MEM_IS_DEFINED(&z,sizeof(z)) will tell is there's a memory leak in z.
summary& understanding after reading <<All of Programming>> Appendix
Comments
Post a Comment