B09 Lab week 5

This is an exercise in trouble-shooting mistakes in using malloc'd space. It is almost a certainty that when it is your turn you will make even worse and harder-to-notice mistakes than the ones in this exercise, so it is important to get started on detecting problematic code.

My program ‘circle.c’ is faulty! Your job is to fix my mistakes. For simplicity, don't worry about “have you checked that malloc is not returning NULL?”—My mistakes are subtler than that!

Valgrind contains a great tool for catching memory usage errors during run time, including array index out of bounds, mistakes in using malloc'd space, and mistakes about freeing space. (Forgetting to free is known as “memory leak”.)

Valgrind is already avaiable on Mathlab. In your own Ubuntu, you can install the C compiler, Valgrind, and related packages by

sudo apt install gcc libc6-dev make manpages-dev glibc-doc valgrind

Compile my circle.c by

gcc -O2 -Wall -g circle.c -o circle -lm

“-g” records “debugging information” such as source code line numbers for use by Valgrind (and other debugging tools). “-lm” requests the math library (because I use sin and cos).

Run it under Valgrind by:

valgrind --leak-check=yes ./circle

If you want Valgrind's report in a file instead, add “--log-file=filename”.

You can declare victory when Valgrind concludes:

ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

(and you actually fix the errors and preserve/restore intended functionality, as opposed to just deleting or trivializing my code!)

Check out Valgrind quick start guide for more explanations and digging deeper. (And man valgrind and valgrind --help as usual.)