Thursday, September 5, 2019

Introduction to debugging C programs using GDB


Instead of just reading the code, a debugger such as GDB, can be used to find errors in C programs. GDB is available in linux distributions.

Example code, prod.c :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <stdlib.h>

int mul(int x, int y){
   int prod;
   int i;

   prod=0;
   for (i=0;i<y;i++){
      prod=prod+x;
   }
   return prod;
}

int main(){
   int a=4;
   int b=3;

   printf("The product of %d and %d is %d\n",a,b,mul(a,b));
   
   return 0;

} 

The following are the typical activities when debugging C programs:

1.  Create the executable with debug information

$ gcc -g -o prod.exe prod.c

For assembly language programs:

$ nasm -g -F dwarf -felf64 prod.asm
$ ld -o prod.exe prod.o


2.  Load the program in GDB

$ gdb prod.exe

3. View the source code listing

(gdb) list
 
4. Set a breakpoint

(gdb) b * main

5. Execute until breakpoint

(gdb) r

6. Execute next line

(gdb) n

7. View current line being executed

(gdb) frame

8. Step into a function

(gdb) s

9. View local variables

(gdb) info locals

10. Print variables

(gdb) print a

11. Set new values for variables

(gdb) set variable a=5

12. Continue execution until next breakpoint

(gdb) c

13. Quit

(gdb) quit