Table of Contents

01. [10p] Valgrind

Dynamic analysis tools can observe a running process and report memory-related issues that static analysis would miss entirely. In this exercise you will use Valgrind to detect memory leaks in a small C program – and get a first taste of the dynamic instrumentation concept that will be developed further in Task 04 with Intel Pin.

[5p] Task A - Writing a leaky program

Read the contents of leak.c and compile it:

$ gcc -g -o leak leak.c

The -g flag includes debug symbols so Valgrind can report exact file names and line numbers.

Now run it normally and observe that nothing seems wrong from the outside:

$ ./leak
$ echo "exit code: $?"

[5p] Task B - Detecting leaks with Valgrind

Run the same binary under Valgrind's memory error detector:

$ valgrind --leak-check=full --show-leak-kinds=all ./leak

Examine the output and answer the following questions:

  1. How many bytes are reported as definitely lost? Does this match what you would expect from reading the source?
  2. What is the difference between definitely lost and indirectly lost in Valgrind's terminology?
  3. At what line number does Valgrind point as the origin of the leak? Why is that line significant rather than the line where the pointer goes out of scope?
  4. Re-compile without the -g flag and run Valgrind again. What information is now missing from the report, and why?

Troubleshooting


On certain distributions such as CachyOS, you may get the following error:

valgrind:  Fatal error at startup: a function redirection
valgrind:  which is mandatory for this platform-tool combination
valgrind:  cannot be set up.  Details of the redirection are:

valgrind need the DWARF debug info for libc in order to function properly. If the ELF file itself doesn't have it, valgrind will try to use debuginfod find to download it using the Build ID stored in the .note.gnu.build-id section. If the debuginfod server doesn't have it either, your only hope of getting it to work is:

  • recompiling glibc with debug symbols (out of the question)
  • starting a docker container with Ubuntu, Debian, Arch Linux, etc.