This is an old revision of the document!


01. [10p] Memory Leaks & Dynamic Analysis

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

Create the following file as leak.c:

#include <stdlib.h>
#include <string.h>
 
void leaky_function() {
    char *buf = malloc(256);
    strcpy(buf, "this memory will never be freed");
    /* buf is never passed to free() */
}
 
int main() {
    for (int i = 0; i < 10; i++)
        leaky_function();
    return 0;
}

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?

HINTS: heap allocation; call stack; debug symbols

ep/labs/04/contents/tasks/ex1.1774293634.txt.gz · Last modified: 2026/03/23 21:20 by radu.mantu
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0