Show Table of Contents
4.3.2. Running GDB
This section will describe a basic execution of GDB, using the following simple program:
hello.c
#include <stdio.h>
char hello[] = { "Hello, World!" };
int
main()
{
fprintf (stdout, "%s\n", hello);
return (0);
}
The following procedure illustrates the debugging process in its most basic form.
Procedure 4.1. Debugging a 'Hello World' Program
- Compile hello.c into an executable with the debug flag set, as in:
gcc -g -o hello hello.cEnsure that the resulting binaryhellois in the same directory ashello.c. - Run
gdbon thehellobinary, that is,gdb hello. - After several introductory comments,
gdbwill display the default GDB prompt:(gdb)
- The variable
hellois global, so it can be seen even before themainprocedure starts:gdb) p hello $1 = "Hello, World!" (gdb) p hello[0] $2 = 72 'H' (gdb) p *hello $3 = 72 'H' (gdb)
Note that theprinttargetshello[0]and*hellorequire the evaluation of an expression, as does, for example,*(hello + 1):(gdb) p *(hello + 1) $4 = 101 'e'
- Next, list the source:
(gdb) l 1 #include <stdio.h> 2 3 char hello[] = { "Hello, World!" }; 4 5 int 6 main() 7 { 8 fprintf (stdout, "%s\n", hello); 9 return (0); 10 }Thelistreveals that thefprintfcall is on line 8. Apply a breakpoint on that line and resume the code:(gdb) br 8 Breakpoint 1 at 0x80483ed: file hello.c, line 8. (gdb) r Starting program: /home/moller/tinkering/gdb-manual/hello Breakpoint 1, main () at hello.c:8 8 fprintf (stdout, "%s\n", hello);
- Finally, use the
nextcommand to step past thefprintfcall, executing it:(gdb) n Hello, World! 9 return (0);
The following sections describe more complex applications of GDB.

Where did the comment section go?
Red Hat's documentation publication system recently went through an upgrade to enable speedier, more mobile-friendly content. We decided to re-evaluate our commenting platform to ensure that it meets your expectations and serves as an optimal feedback mechanism. During this redesign, we invite your input on providing feedback on Red Hat documentation via the discussion platform.