<aside> ✅ Valgrind is a tool primarily used to detect and analyze memory access errors in a program.
</aside>
Firstly, we want to compile our program with debug flags so that Valgrind can provide more information, such as line numbers. To do this, we compile with the '-g' flag:
clang -Wall -g -o <program-name> <c-file>
To run the program with Valgrind, we use the following command:
valgrind --leak-check=full ./<program-name>
The flag 'leak-check=full' specifies how much additional information Valgrind displays. Further explanations of the flags can be found here. Additional information about the Valgrind summary can be found in the here.
<aside> ✅ When you use our testrunner to review your solution (’make test’), a subfolder called ‘valgrind_logs’ is generated which includes a Valgrind summary for each testcase. You can also access them in the testreport.html file in the summary view:
</aside>
$ clang -Wall -g -o valgrind_example valgrind_example.c
$ valgrind --leak-check=full ./valgrind_example
==16270== Memcheck, a memory error detector
==16270== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16270== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==16270== Command: ./valgrind_example
==16270==
Result: 3
==16270==
==16270== HEAP SUMMARY:
==16270== in use at exit: 8 bytes in 1 blocks
==16270== total heap usage: 2 allocs, 1 frees, 1,032 bytes allocated
==16270==
==16270== **8 bytes in 1 blocks** are definitely lost in loss record 1 of 1
==16270== at 0x483A7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==16270== by 0x401167: main **(valgrind_example.c:36)**
==16270==
==16270== LEAK SUMMARY:
==16270== **definitely lost: 8 bytes in 1 blocks**
==16270== indirectly lost: 0 bytes in 0 blocks
==16270== possibly lost: 0 bytes in 0 blocks
==16270== still reachable: 0 bytes in 0 blocks
==16270== suppressed: 0 bytes in 0 blocks
==16270==
==16270== For lists of detected and suppressed errors, rerun with: -s
==16270== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
In the file 'valgrind_example' we allocated 8 bytes with malloc() at line 36, but we did not free them with free(). Therefore, these 8 bytes are 'definitely lost' after the program ends.