Previous Page
Next Page

16.14. Debugging

Using the macro assert( ) is a simple way to find logical mistakes during program development. This macro is defined in the header assert.h. It simply tests its scalar argument for a nonzero value. If the argument's value is zero, assert( ) prints an error message that lists the argument expression, the function, the filename, and the line number, and then calls abort( ) to stop the program. In the following example, the assert( ) calls perform some plausibility checks on the argument to be passed to free( ):

    #include <stdlib.h>
    #include <assert.h>
    char *buffers[64] = { NULL };   // An array of pointers
    int i;
    /* ... allocate some memory buffers; work with them ... */
      assert( i >= 0 && i < 64 );     // Index out of range?
      assert( buffers[i] != NULL );   // Was the pointer used at all?
      free( buffers[i] );

Rather than trying to free a nonexistent buffer, this code aborts the program (here compiled as assert.c) with the following diagnostic output:

    assert: assert.c:14: main: Assertion `buffers[i] != ((void *)0)' failed.

When you have finished testing, you can disable all assert( ) calls by defining the macro NDEBUG before the #include directive for assert.h. The macro does not need to have a replacement value. For example:

    #define NDEBUG
    #include <assert.h>
    /* ... */

Previous Page
Next Page