how to debug c code using gdb

Q: what is gdb debugger?
A: GDB, the GNU Project debugger, allows you to see what is going on `inside’ another program while it executes or what another program was doing at the moment it crashed.

1. Put the following code in sample.c file

 

#include <stdio.h>

int main()
{
  int i, num, j;
  printf ("Enter the number: ");
  scanf ("%d", &num );
  for (i=1; i<num; i++)
    j=j*i;
  printf("The factorial of %d is %d\n",num,j);
}

2. then compile it using following command:
cc -g -Wall sample.c # -g for compile and -Wall for warning messages

3. gdb a.out

4. Now your gdb console is open for debugging.

5. Commands for debugning

list: to view the source code.
b function_name/ line number
b file_name:line_number # fuction exist in sum other file
# b => break point

r execute program

n for execute next line

display var_name # value of var_name will be printed every time (when you hit n      command)

c # continue the program as normal.

info var_name # information of variable

s # step into the fucntion.
For Ruby
https://robots.thoughtbot.com/using-gdb-to-inspect-a-running-ruby-process

Leave a comment