Profiling C programs

A profiler executes a program while tracking information about it. One major application where a profiler is useful is in detecting memory leaks.

Our laboratory computers have a profiler on it called valgrind. It can be invoked only from the command line.

  1. You first want to make sure your program is compiled with debugging information included. To do this, include the “-g” option on the command line:

    linux% gcc -g -Wall *.c
    
  2. Now tell valgrind to execute your program while profiling it:

    linux% valgrind --leak-check=full ./a.out
    
  3. The output will be formatted as follows:

    ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
    malloc/free: in use at exit: 200 bytes in 1 blocks.
    malloc/free: 1 allocs, 0 frees, 200 bytes allocated.
    For counts of detected errors, rerun with: -v
    searching for pointers to 1 not-freed blocks.
    checked 59,148 bytes.
    
    200 bytes in 1 blocks are definitely lost in loss record 1 of 1
       at 0x4022AB8: malloc (vg_replace_malloc.c:207)
       by 0x80483CC: main (test.c:6)
    
    LEAK SUMMARY:
       definitely lost: 200 bytes in 1 blocks.
         possibly lost: 0 bytes in 0 blocks.
       still reachable: 0 bytes in 0 blocks.
            suppressed: 0 bytes in 0 blocks.
    

    First look for the “definitely lost” line in the “leak summary.” If this indicates 0 blocks of lost memory, then there are no leaks. If there is a leak, then it will be described prior to the “leak summary”, including a partial stack trace indicating where in the program the program was at the time of allocation. In this case, the trace says test.c:6 called malloc, indicating that line 6 of my program is where the unfreed memory was initially allocated.