≑ Menu

How to Debug C Program using gdb in 6 Simple Steps

Earlier we discussed the basics of how to write and compile a C program with C Hello World Program.

In this article, let us discuss how to debug a c program using gdb debugger in 6 simple steps.

Write a sample C program with errors for debugging purpose

To learn C program debugging, let us create the following C program that calculates and prints the factorial of a number. However this C program contains some errors in it for our debugging purpose.

$ vim factorial.c
# 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);
}
$ cc factorial.c

$ ./a.out
Enter the number: 3
The factorial of 3 is 12548672

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 factorial.c

Note: The above command creates a.out file which will be used for debugging as shown below.

Step 2. Launch gdb

Launch the C debugger (gdb) as shown below.

$ gdb a.out

Step 3. Set up a break point inside C program

Syntax:

break line_number

Other formats:

  • break [file_name]:line_number
  • break [file_name]:func_name

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.

break 10
Breakpoint 1 at 0x804846f: file factorial.c, line 10.

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 give run, and start the program execution.

run
Starting program: /home/sathiyamoorthy/Debugging/c/a.out

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

Breakpoint 1, main () at factorial.c:10
10			j=j*i;

You can use various gdb commands to debug the C program as explained in the sections below.

Step 5. Printing the variable values inside gdb debugger

Syntax: print {variable}

Examples:
print i
print j
print num
(gdb) p i
$1 = 1
(gdb) p j
$2 = 3042592
(gdb) p num
$3 = 3
(gdb)

As you see above, in the factorial.c, we have not initialized the variable j. So, it gets garbage value resulting in a big numbers as factorial values.

Fix this issue by initializing variable j with 1, compile the C program and execute it again.

Even after this fix there seems to be some problem in the factorial.c program, as it still gives wrong factorial value.

So, place the break point in 10th line, and continue as explained in the next section.

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.

By continuing or stepping through you could have found that the issue is because we have not used the <= in the ‘for loop’ condition checking. So changing that from < to <= will solve the issue.

gdb command shortcuts

Use following shortcuts for most of the frequent gdb operations.

  • l – list
  • p – print
  • c – continue
  • s – step
  • ENTER: pressing enter key would execute the previously executed command again.

Miscellaneous gdb commands

  • l command: Use gdb command l or list to print the source code in the debug mode. Use l line-number to view a specific line number (or) l function to view a specific function.
  • bt: backtrack – Print backtrace of all stack frames, or innermost COUNT frames.
  • help – View help for a particular gdb topic — help TOPICNAME.
  • quit – Exit from the gdb debugger.
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Seif Abaza March 15, 2010, 4:13 am

    I think it’s the same way through regular gcc but the new is cc

    thank you πŸ™‚

  • shadyabhi March 16, 2010, 5:44 am

    cc just runs the default compiler… ie gcc..

  • vasiauvi March 16, 2010, 8:49 am

    Today just bought 2 C Programming books and I will try this things in Linux. Until now just programmed only in WindowsXP.
    Thanks!

  • Rick Stanley March 16, 2010, 10:01 am

    Under Debian Linux, cc is a soft link to gcc. They are the same compiler. I don’t have other distros handy right now, but I assume the same for most if not all.

  • Der Gentorzist March 25, 2010, 10:15 am

    Also recommendable is to start gdb with -tui. Simply more intuitive, the interface.

  • Selma April 16, 2010, 11:59 am

    PLease, can anyone tell me why does not the command run work for me??
    it’s written after typing it(run) :bash: run: command not found
    Thank you.

  • SathiyaMoorthy April 17, 2010, 8:52 am

    You have to execute the run command in the gdb command line, and not in the bash command line.

  • Saman August 19, 2010, 11:56 am

    Thanks for this post. I think you should replace “backtrack” with “backtrace”. After step 1 you didn’t mentioned about running gdb [program_name] in the terminal. am I right?

  • Saman August 19, 2010, 12:00 pm

    @Der Gentorzist
    Thanks for the tip. you can use gdbtui command too.

  • balachandran September 17, 2010, 5:34 am

    ple any one tell debugging details….

  • Krishnendu March 28, 2011, 2:24 am

    Very very thanks..It will help me a lots …..

  • Nav June 18, 2011, 6:50 am

    Nice post! Nice website colours and layout! Thanks for this useful starting info on GDB.

  • jeevitha September 7, 2011, 11:41 pm

    ple tell debugging details

  • abhinav singh September 23, 2011, 2:47 pm

    really helpful tips…

  • Anonymous September 28, 2011, 4:23 am

    thanx a lot…… really helpful

  • kamal February 9, 2012, 7:04 am

    thanks

  • saravanan M.C.A February 16, 2012, 10:17 am

    I learn many information in this website thanks………………

  • nothing1010 February 18, 2012, 8:08 am

    thanks you very much! really helpful! love you…

  • gayu February 27, 2012, 12:53 am

    very useful cmd

  • POOJAH February 27, 2012, 12:55 am

    REALLY VERY HELPFUL COMMAND

  • subash February 27, 2012, 8:58 am

    very good

  • dhinesh March 10, 2012, 8:15 am

    thanks

  • STANTHEMAN March 12, 2012, 11:11 pm

    this explained it better then my professor, book, or any other references he gave us. If only i found the right search on google sooner…

  • gowtham m.c.a March 22, 2012, 12:14 am

    piz get in more information

  • yuvaraj M.C.A ,M,phil,Phd March 22, 2012, 12:17 am

    i like very much & get more information

  • Asish April 13, 2012, 12:36 am

    Thanks! Its very useful and nicely explained..

  • Dur n' Lev June 18, 2012, 11:49 pm

    Thanks. The nice guide. Simple and quick to get it works

  • saravanan.p bca August 29, 2012, 7:18 am

    thanks to c in debug. plz get in more information

  • Jayanthi T September 1, 2012, 10:05 am

    It’s very useful. thank u

  • Anonymous September 26, 2012, 3:29 pm

    What can I do to learn what you guys are talking about?

  • RS Naidu October 14, 2012, 9:13 am

    Hi SathiyaMoorthy,

    It is very useful and was very nicely explained.

    Thank you,

    Regards,
    RS Naidu

  • Kalpesh Adhatrao November 3, 2012, 8:18 am

    Reall nice article sir, thank you πŸ™‚

  • Avishay December 8, 2012, 12:57 pm

    L lost the -g in my namefile and the debugger and could not understand when no breakpoints work.
    that was a great help.
    THANK YOU!

  • Rahul December 17, 2012, 11:41 pm

    very very well explained with simple example .

  • ravi sanker December 19, 2012, 6:05 am

    by using which compiler we can give the input to our program

  • ramiya January 31, 2013, 3:10 am

    @Ravi sanker in the tutorial they are using cc but if you want you can use GNU C compiler aka GCC also.

  • bayapureddy March 27, 2013, 11:13 am

    Thank you.

  • shamika March 30, 2013, 1:18 am

    Awesome clear explanation.Thankx.

  • ag April 4, 2013, 11:35 am

    One of the best concise tutorials I’ve seen on any topic. Thanks!

  • kamal babu August 6, 2013, 8:33 pm

    A very usefull debugger for a linux programmer.
    Can you tell me is there any more commands to learn.
    so that I can be get a grip on gdb.

  • archana August 13, 2013, 11:57 pm

    havent understood the run [args ] part .. can u narrate the path more clearly

  • Felipe August 24, 2013, 11:41 am

    Thank you very much! It finally helped to learn the basics of gdb in 10 minutes. Great work!

  • sree August 28, 2013, 8:03 am

    thank you, Moorthy sir.

  • sreenath.mp August 31, 2013, 12:08 am

    Thank you friends

    I get most wanted information about the compiling and running steps of c programming within few minutes.
    great site for information……

  • Ranjitha September 6, 2013, 9:17 pm

    Please send me best C debugging books details.

  • Anonymous September 13, 2013, 1:40 am

    is it work for c++ if we change the compiler name gcc to g++ .

  • Snehasish Karmakar March 27, 2014, 9:20 am

    Nice article, Sir. One question. Would you please tell me how to edit the source file or a function or a line in the source file from gdb. I don’t know whether it is possible or not though.

  • Anoop April 15, 2014, 3:16 am

    Send me best C debugging books details.:-)

  • DW April 17, 2014, 6:12 pm

    Very good intro to gdb!

  • mahesh July 10, 2014, 8:24 am

    Really very nice sir.

  • Raji August 6, 2014, 6:24 am

    Thanks, it will helpfull to beginners.

  • Anonymous January 5, 2015, 12:03 am

    very helpfull

  • Anonymous January 14, 2015, 2:30 pm

    Its a very clear explanation, helped me to understand very quickly. Helpful !!

  • ASHUTOSH TIWARI January 22, 2015, 9:37 am

    clear defined debugging relay help full

  • haileab solomon May 5, 2015, 1:23 am

    i got a code from the internet and when i run the code it keep me says the debugging file does not exist what shall i do?

  • rajesh August 20, 2015, 3:28 am

    i want to know how backened program runs ,in assembly language.
    and if any books is there just mention the book name

  • aelvi ramya September 12, 2015, 2:32 am

    super sir

  • Vivek November 21, 2015, 8:33 am

    Very useful information,nicely explained, thanks

  • praveen January 16, 2016, 3:49 pm

    step 3 is little confusing.
    where to write `break line_number` in side a code or inside gdb dubbuger(when we do gdb a.out) ?

  • Checho February 28, 2016, 9:49 pm

    Code is wrong, j always 0, this is the right one:
    # include

    int main()
    {
    int i, num, j=1;
    printf (“Enter the number: “);
    scanf (“%d”, &num );

    for (i=1; i<num; i++){
    printf("%d\n", j);
    j=j*(i+1);
    }

    printf("The factorial of %d is %d\n",num,j);
    }

  • DHIVYA March 11, 2016, 2:50 am

    Thank u and very useful for me

  • anusuya March 11, 2016, 2:58 am

    thanx……….

  • Dhivya March 11, 2016, 3:00 am

    very Useful For Me

  • Farhan December 21, 2016, 12:21 pm

    Can you provide an explanation of how and when to use tracepoints

  • Raj January 30, 2017, 11:22 pm

    Thanks Ramesh for a simple concise detail about gdb debugging !! Really helped !!

  • Alex March 28, 2019, 2:14 am

    It is help me. Thanks.