Listing 1: Sample program that contains intentional bug to demonstrate use of gdb

/*  test01.c - Show some features of gdb.  */
/*  Note that this program has an INTENTIONAL bug, since this  */
/*  is an article about debugging!  */

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void
sigfunc1( int sig )
{
    printf( "Got signal %d\n", sig );
    exit( 1 );
}

void
sigfunc2( int sig )
{
    printf( "Got signal %d\n", sig );
    return;
}

int
func4( char *ptr )
{
    printf( "strlen( \"%s\" ) = %d\n", ptr, strlen( ptr ));
    return 0;
}

int
func3( int i )
{
    char        *p = NULL;

    if (i) {
        p = malloc( i+1 );
        memset( p, 0, i+1 );
        while (i--)
            p[i] = '0' + (i % 10);
    }
    func4( p );
    if (p)
        free( p );
    return 0;
}

int
main()
{
    signal( SIGHUP, sigfunc1 );
    signal( SIGINT, sigfunc2 );
    func3(30);
    func3(10);
    func3(0);
    func3(20);
    return 0;
}

/*  Output:
strlen( "012345678901234567890123456789" ) = 30
strlen( "0123456789" ) = 10
Segmentation fault (core dumped)
*/
— End of Listing —