How to debug your C code

You have written your program, everything correctly compiles, but when you finally run it, it does not work. What do you do?

Trace Messages

A very useful technique for debugging is to put trace messages into your code. Trace messages are little comments which the program outputs to tell you how it is running. You can use trace messages to discover where in your program an error occurs, to print out intermediate calculations so that you can see that the program is computing correctly, or any other data that you need.

You place trace messages by putting printf() statements in your code at strategic locations. For example, you can place messages before and after procedure calls so you can determine when the program crashes, or you can place messages inside loops so you can see the values of intermediate calculations. Be certain to remove these trace messages before submitting your assignment.

Here is an example of the use of trace messages.

int main(void)
{
    int array[SIZE];

    if (!inputdata(array))
        return 0;
printf("Successfully returned from inputdata()\n");  /* TRACE MESSAGE */

    sort(array);
printf("Successfully returned from sort()\n");       /* TRACE MESSAGE */

    for (i = 0; i < size; i++)
    {
        total += factorial(array[i]);
printf("iteration %d, total is now %d\n", i, total); /* TRACE MESSAGE */
        array[i] -= total;
    }

printf("Now calling outputdata()\n");                /* TRACE MESSAGE */
    outputdata(array);
    return 0;
}

Debuggers

The C debugger on CDF is gdb. gdb allows you to run your program step by step so that you can see the result of each line of your code. To use gdb, you must compile your executable with the -g flag.

gcc -g -o myexec myprogram.c

Then you can run your program in gdb.

gdb myexec

gdb will first load information on your program and then give you a prompt. Here are some useful commands.

Read the man page of gdb, "man gdb", for more information.

Common Errors

The most common errors are the bus error and the segmentation violation, also called a segmentation fault or a segv. The main cause of these errors is that your program is accessing an illegal area of memory. The most common causes are pointers with incorrect values, uninitialized pointers, or accessing an array beyond its last element, or before its first element. Another common cause is passing the value of a variable to a function which expects the address of the variable (ex: scanf()).


Click here to go back to the menu, if your browser does not support frames.