Debugging




To learn C program debugging, let us create the following C program that displays the multiplication table for given number.

#include <stdio.h >
main()
{

    int n,i=1;
    printf("Enter no:\t");
    scanf("%d",&n);
    while(i <10)
    {
        printf("%d x %d = %d\n",n,i,n*i);
        i++;
    }
}


Here is the output of above file


But what if I want to trace the loop? In that case I can use gdb tool as follows


Let us debug it while reviewing the most useful commands in gdb.

Step 1. Compile the C program with debugging option -g

Compile your C program with -g option. This allows the compiler to collect the debugging information.

$ cc -g counting_table.c -o counting 
 
Note: The above command creates counting file which will be used for 
debugging as shown below. 
 

Step 2. Launch gdb

Launch the C debugger (gdb) as shown below.
 
$ gdb counting
 

Step 3. Set up a break point inside C program

Syntax: break line_number


Places break point in the C program, where you suspect errors. While executing the program, the debugger will stop at the break point, and gives you the prompt to debug.
So before starting up the program, let us place the following break point in our program.


(gdb) break 11
Breakpoint 1 at 0x80484cb: file counting_table.c, line 11.

Step 4. Execute the C program in gdb debugger

run [args]
 
You can start running the program using the run command in the gdb debugger. You can also give command line arguments to the program via run args. The example program we used here does not requires any command line arguments so let us run, and start the program execution.

(gdb) run
Starting program: /home/ramdas/fybcs_2015/counting
Enter no:       4
4 x 1 = 4

Breakpoint 1, main () at counting_table.c:11
warning: Source file is more recent than executable.
11                      i++;

Once you executed the C program, it would execute until the first break point, and give you the prompt for debugging.

Step 5. Printing the variable values inside gdb debugger

Syntax: print {variable}

Examples:
(gdb) p i 
$1 = 1
(gdb) p n*i
$2 = 4
(gdb) 

Step 6. Continue, stepping over and in – gdb commands

There are three kind of gdb operations you can choose when the program stops at a break point. They are continuing until the next break point, stepping in, or stepping over the next program lines.
  • c or continue: Debugger will continue executing until the next break point.
  • n or next: Debugger will execute the next line as single instruction.
  • s or step: Same as next, but does not treats function as a single instruction, instead goes into the function and executes it line by line.


1 comment:

  1. assemblear program sym lit pool table program send karo please argent
    rajumungase.rm@gmail.com

    ReplyDelete