SlideShare a Scribd company logo
1 of 21
Download to read offline
GDB Tutorial
A Walkthrough with Examples
CMSC 212 - Spring 2009
Last modified March 22, 2009
GDB Tutorial
What is gdb?
“GNU Debugger”
A debugger for several languages, including C and C++
It allows you to inspect what the program is doing at a certain
point during execution.
Errors like segmentation faults may be easier to find with the
help of gdb.
http://sourceware.org/gdb/current/onlinedocs/gdb toc.html -
online manual
GDB Tutorial
Additional step when compiling program
Normally, you would compile a program like:
gcc [flags] <source files> -o <output file>
For example:
gcc -Wall -Werror -ansi -pedantic-errors prog1.c -o prog1.x
Now you add a -g option to enable built-in debugging support
(which gdb needs):
gcc [other flags] -g <source files> -o <output file>
For example:
gcc -Wall -Werror -ansi -pedantic-errors -g prog1.c -o prog1.x
GDB Tutorial
Starting up gdb
Just try “gdb” or “gdb prog1.x.” You’ll get a prompt that looks
like this:
(gdb)
If you didn’t specify a program to debug, you’ll have to load it in
now:
(gdb) file prog1.x
Here, prog1.x is the program you want to load, and “file” is the
command to load it.
GDB Tutorial
Before we go any further
gdb has an interactive shell, much like the one you use as soon as
you log into the linux grace machines. It can recall history with the
arrow keys, auto-complete words (most of the time) with the TAB
key, and has other nice features.
Tip
If you’re ever confused about a command or just want more
information, use the “help” command, with or without an
argument:
(gdb) help [command]
You should get a nice description and maybe some more useful
tidbits. . .
GDB Tutorial
Running the program
To run the program, just use:
(gdb) run
This runs the program.
If it has no serious problems (i.e. the normal program didn’t
get a segmentation fault, etc.), the program should run fine
here too.
If the program did have issues, then you (should) get some
useful information like the line number where it crashed, and
parameters to the function that caused the error:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400524 in sum array region (arr=0x7fffc902a270, r1=2, c1=5,
r2=4, c2=6) at sum-array-region2.c:12
GDB Tutorial
So what if I have bugs?
Okay, so you’ve run it successfully. But you don’t need gdb for
that. What if the program isn’t working?
Basic idea
Chances are if this is the case, you don’t want to run the program
without any stopping, breaking, etc. Otherwise, you’ll just rush past the
error and never find the root of the issue. So, you’ll want to step through
your code a bit at a time, until you arrive upon the error.
This brings us to the next set of commands. . .
GDB Tutorial
Setting breakpoints
Breakpoints can be used to stop the program run in the middle, at
a designated point. The simplest way is the command “break.”
This sets a breakpoint at a specified file-line pair:
(gdb) break file1.c:6
This sets a breakpoint at line 6, of file1.c. Now, if the program
ever reaches that location when running, the program will pause
and prompt you for another command.
Tip
You can set as many breakpoints as you want, and the program
should stop execution if it reaches any of them.
GDB Tutorial
More fun with breakpoints
You can also tell gdb to break at a particular function. Suppose
you have a function my func:
int my func(int a, char *b);
You can break anytime this function is called:
(gdb) break my func
GDB Tutorial
Now what?
Once you’ve set a breakpoint, you can try using the run
command again. This time, it should stop where you tell it to
(unless a fatal error occurs before reaching that point).
You can proceed onto the next breakpoint by typing
“continue” (Typing run again would restart the program
from the beginning, which isn’t very useful.)
(gdb) continue
You can single-step (execute just the next line of code) by
typing “step.” This gives you really fine-grained control over
how the program proceeds. You can do this a lot...
(gdb) step
GDB Tutorial
Now what? (even more!)
Similar to “step,” the “next” command single-steps as well,
except this one doesn’t execute each line of a sub-routine, it
just treats it as one instruction.
(gdb) next
Tip
Typing “step” or “next” a lot of times can be tedious. If you just
press ENTER, gdb will repeat the same command you just gave it.
You can do this a bunch of times.
GDB Tutorial
Querying other aspects of the program
So far you’ve learned how to interrupt program flow at fixed,
specified points, and how to continue stepping line-by-line.
However, sooner or later you’re going to want to see things
like the values of variables, etc. This might be useful in
debugging. :)
The print command prints the value of the variable
specified, and print/x prints the value in hexadecimal:
(gdb) print my var
(gdb) print/x my var
GDB Tutorial
Setting watchpoints
Whereas breakpoints interrupt the program at a particular line or
function, watchpoints act on variables. They pause the program
whenever a watched variable’s value is modified. For example, the
following watch command:
(gdb) watch my var
Now, whenever my var’s value is modified, the program will
interrupt and print out the old and new values.
Tip
You may wonder how gdb determines which variable named my var to watch if there
is more than one declared in your program. The answer (perhaps unfortunately) is
that it relies upon the variable’s scope, relative to where you are in the program at the
time of the watch. This just means that you have to remember the tricky nuances of
scope and extent :(.
GDB Tutorial
Example programs
Some example files are found in
~/212public/gdb-examples/broken.c on the linux grace
machines.
Contains several functions that each should cause a
segmentation fault. (Try commenting out calls to all but one
in main())
The errors may be easy, but try using gdb to inspect the code.
GDB Tutorial
Other useful commands
backtrace - produces a stack trace of the function calls that
lead to a seg fault (should remind you of Java exceptions)
where - same as backtrace; you can think of this version as
working even when you’re still in the middle of the program
finish - runs until the current function is finished
delete - deletes a specified breakpoint
info breakpoints - shows information about all declared
breakpoints
Look at sections 5 and 9 of the manual mentioned at the beginning
of this tutorial to find other useful commands, or just try help.
GDB Tutorial
gdb with Emacs
Emacs also has built-in support for gdb. To learn about it, go here:
http://tedlab.mit.edu/~dr/gdbintro.html
GDB Tutorial
More about breakpoints
Breakpoints by themselves may seem too tedious. You have to
keep stepping, and stepping, and stepping. . .
Basic idea
Once we develop an idea for what the error could be (like dereferencing a
NULL pointer, or going past the bounds of an array), we probably only
care if such an event happens; we don’t want to break at each iteration
regardless.
So ideally, we’d like to condition on a particular requirement (or set
of requirements). Using conditional breakpoints allow us to
accomplish this goal. . .
GDB Tutorial
Conditional breakpoints
Just like regular breakpoints, except that you get to specify some
criterion that must be met for the breakpoint to trigger. We use
the same break command as before:
(gdb) break file1.c:6 if i >= ARRAYSIZE
This command sets a breakpoint at line 6 of file file1.c, which
triggers only if the variable i is greater than or equal to the size of
the array (which probably is bad if line 6 does something like
arr[i]). Conditional breakpoints can most likely avoid all the
unnecessary stepping, etc.
GDB Tutorial
Fun with pointers
Who doesn’t have fun with pointers? First, let’s assume we have
the following structure defined:
struct entry {
int key;
char *name;
float price;
long serial_number;
};
Maybe this struct is used in some sort of hash table as part of a
catalog for products, or something related.
GDB Tutorial
Using pointers with gdb I
Now, let’s assume we’re in gdb, and are at some point in the execution
after a line that looks like:
struct entry * e1 = <something>;
We can do a lot of stuff with pointer operations, just like we could in C.
See the value (memory address) of the pointer:
(gdb) print e1
See a particular field of the struct the pointer is referencing:
(gdb) print e1->key
(gdb) print e1->name
(gdb) print e1->price
(gdb) print e1->serial number
GDB Tutorial
Using pointers with gdb II
You can also use the dereference (*) and dot (.) operators in place
of the arrow operator (->):
(gdb) print (*e1).key
(gdb) print (*e1).name
(gdb) print (*e1).price
(gdb) print (*e1).serial number
See the entire contents of the struct the pointer references (you
can’t do this as easily in C!):
(gdb) print *e1
You can also follow pointers iteratively, like in a linked list:
(gdb) print list prt->next->next->next->data
GDB Tutorial

More Related Content

What's hot

Debugging Applications with GNU Debugger
Debugging Applications with GNU DebuggerDebugging Applications with GNU Debugger
Debugging Applications with GNU DebuggerPriyank Kapadia
 
Debugging With GNU Debugger GDB
Debugging With GNU Debugger GDBDebugging With GNU Debugger GDB
Debugging With GNU Debugger GDBkyaw thiha
 
GDB: A Lot More Than You Knew
GDB: A Lot More Than You KnewGDB: A Lot More Than You Knew
GDB: A Lot More Than You KnewUndo
 
Give me 15 minutes and i'll change your view of gdb
Give me 15 minutes and i'll change your view of gdbGive me 15 minutes and i'll change your view of gdb
Give me 15 minutes and i'll change your view of gdbgregthelaw
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about CYi-Hsiu Hsu
 
GCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programsGCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programsDaniel Ilunga
 
How it's made: C++ compilers (GCC)
How it's made: C++ compilers (GCC)How it's made: C++ compilers (GCC)
How it's made: C++ compilers (GCC)Sławomir Zborowski
 
Compiling Under Linux
Compiling Under LinuxCompiling Under Linux
Compiling Under LinuxPierreMASURE
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005Saleem Ansari
 
C Under Linux
C Under LinuxC Under Linux
C Under Linuxmohan43u
 
Goroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in GoGoroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in GoYu-Shuan Hsieh
 
Qtpvbscripttrainings
QtpvbscripttrainingsQtpvbscripttrainings
QtpvbscripttrainingsRamu Palanki
 
Debugging Modern C++ Application with Gdb
Debugging Modern C++ Application with GdbDebugging Modern C++ Application with Gdb
Debugging Modern C++ Application with GdbSenthilKumar Selvaraj
 
Improving GStreamer performance on large pipelines: from profiling to optimiz...
Improving GStreamer performance on large pipelines: from profiling to optimiz...Improving GStreamer performance on large pipelines: from profiling to optimiz...
Improving GStreamer performance on large pipelines: from profiling to optimiz...Luis Lopez
 
GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?Saket Pathak
 

What's hot (20)

Debugging Applications with GNU Debugger
Debugging Applications with GNU DebuggerDebugging Applications with GNU Debugger
Debugging Applications with GNU Debugger
 
Debugging With GNU Debugger GDB
Debugging With GNU Debugger GDBDebugging With GNU Debugger GDB
Debugging With GNU Debugger GDB
 
GDB: A Lot More Than You Knew
GDB: A Lot More Than You KnewGDB: A Lot More Than You Knew
GDB: A Lot More Than You Knew
 
Give me 15 minutes and i'll change your view of gdb
Give me 15 minutes and i'll change your view of gdbGive me 15 minutes and i'll change your view of gdb
Give me 15 minutes and i'll change your view of gdb
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about C
 
GCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programsGCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programs
 
Gccgdb
GccgdbGccgdb
Gccgdb
 
How it's made: C++ compilers (GCC)
How it's made: C++ compilers (GCC)How it's made: C++ compilers (GCC)
How it's made: C++ compilers (GCC)
 
Compiling Under Linux
Compiling Under LinuxCompiling Under Linux
Compiling Under Linux
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005
 
GCC, GNU compiler collection
GCC, GNU compiler collectionGCC, GNU compiler collection
GCC, GNU compiler collection
 
G++ & GCC
G++ & GCCG++ & GCC
G++ & GCC
 
C Under Linux
C Under LinuxC Under Linux
C Under Linux
 
Goroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in GoGoroutine stack and local variable allocation in Go
Goroutine stack and local variable allocation in Go
 
Qtpvbscripttrainings
QtpvbscripttrainingsQtpvbscripttrainings
Qtpvbscripttrainings
 
GCC compiler
GCC compilerGCC compiler
GCC compiler
 
Debugging Modern C++ Application with Gdb
Debugging Modern C++ Application with GdbDebugging Modern C++ Application with Gdb
Debugging Modern C++ Application with Gdb
 
GStreamer Instruments
GStreamer InstrumentsGStreamer Instruments
GStreamer Instruments
 
Improving GStreamer performance on large pipelines: from profiling to optimiz...
Improving GStreamer performance on large pipelines: from profiling to optimiz...Improving GStreamer performance on large pipelines: from profiling to optimiz...
Improving GStreamer performance on large pipelines: from profiling to optimiz...
 
GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?
 

Viewers also liked

Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014ryanerickson
 
Nginx+lua在阿里巴巴的使用
Nginx+lua在阿里巴巴的使用Nginx+lua在阿里巴巴的使用
Nginx+lua在阿里巴巴的使用OpenRestyCon
 
Perl在nginx里的应用
Perl在nginx里的应用Perl在nginx里的应用
Perl在nginx里的应用琛琳 饶
 
基于OpenResty的百万级长连接推送
基于OpenResty的百万级长连接推送基于OpenResty的百万级长连接推送
基于OpenResty的百万级长连接推送OpenRestyCon
 
The basics and design of lua table
The basics and design of lua tableThe basics and design of lua table
The basics and design of lua tableShuai Yuan
 
高性能Web服务器Nginx及相关新技术的应用实践
高性能Web服务器Nginx及相关新技术的应用实践高性能Web服务器Nginx及相关新技术的应用实践
高性能Web服务器Nginx及相关新技术的应用实践rewinx
 
Fusion Middleware Application Grid
Fusion Middleware Application GridFusion Middleware Application Grid
Fusion Middleware Application GridMark Rabne
 
Using ngx_lua / lua-nginx-module in pixiv
Using ngx_lua / lua-nginx-module in pixivUsing ngx_lua / lua-nginx-module in pixiv
Using ngx_lua / lua-nginx-module in pixivShunsuke Michii
 
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明National Cheng Kung University
 
Load balancing in the SRE way
Load balancing in the SRE wayLoad balancing in the SRE way
Load balancing in the SRE wayShawn Zhu
 
Microservices & API Gateways
Microservices & API Gateways Microservices & API Gateways
Microservices & API Gateways Kong Inc.
 
C/C++调试、跟踪及性能分析工具综述
C/C++调试、跟踪及性能分析工具综述C/C++调试、跟踪及性能分析工具综述
C/C++调试、跟踪及性能分析工具综述Xiaozhe Wang
 
TIP1 - Overview of C/C++ Debugging/Tracing/Profiling Tools
TIP1 - Overview of C/C++ Debugging/Tracing/Profiling ToolsTIP1 - Overview of C/C++ Debugging/Tracing/Profiling Tools
TIP1 - Overview of C/C++ Debugging/Tracing/Profiling ToolsXiaozhe Wang
 
Oracle architecture ppt
Oracle architecture pptOracle architecture ppt
Oracle architecture pptDeepak Shetty
 

Viewers also liked (18)

Gdb remote debugger
Gdb remote debuggerGdb remote debugger
Gdb remote debugger
 
Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014
 
Nginx+lua在阿里巴巴的使用
Nginx+lua在阿里巴巴的使用Nginx+lua在阿里巴巴的使用
Nginx+lua在阿里巴巴的使用
 
Learn C Programming Language by Using GDB
Learn C Programming Language by Using GDBLearn C Programming Language by Using GDB
Learn C Programming Language by Using GDB
 
Perl在nginx里的应用
Perl在nginx里的应用Perl在nginx里的应用
Perl在nginx里的应用
 
基于OpenResty的百万级长连接推送
基于OpenResty的百万级长连接推送基于OpenResty的百万级长连接推送
基于OpenResty的百万级长连接推送
 
Nginx-lua
Nginx-luaNginx-lua
Nginx-lua
 
The basics and design of lua table
The basics and design of lua tableThe basics and design of lua table
The basics and design of lua table
 
高性能Web服务器Nginx及相关新技术的应用实践
高性能Web服务器Nginx及相关新技术的应用实践高性能Web服务器Nginx及相关新技术的应用实践
高性能Web服务器Nginx及相关新技术的应用实践
 
Fusion Middleware Application Grid
Fusion Middleware Application GridFusion Middleware Application Grid
Fusion Middleware Application Grid
 
Using ngx_lua / lua-nginx-module in pixiv
Using ngx_lua / lua-nginx-module in pixivUsing ngx_lua / lua-nginx-module in pixiv
Using ngx_lua / lua-nginx-module in pixiv
 
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
給自己更好未來的 3 個練習:嵌入式作業系統設計、實做,與移植 (2015 年春季 ) 課程說明
 
Load balancing in the SRE way
Load balancing in the SRE wayLoad balancing in the SRE way
Load balancing in the SRE way
 
Microservices & API Gateways
Microservices & API Gateways Microservices & API Gateways
Microservices & API Gateways
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 
C/C++调试、跟踪及性能分析工具综述
C/C++调试、跟踪及性能分析工具综述C/C++调试、跟踪及性能分析工具综述
C/C++调试、跟踪及性能分析工具综述
 
TIP1 - Overview of C/C++ Debugging/Tracing/Profiling Tools
TIP1 - Overview of C/C++ Debugging/Tracing/Profiling ToolsTIP1 - Overview of C/C++ Debugging/Tracing/Profiling Tools
TIP1 - Overview of C/C++ Debugging/Tracing/Profiling Tools
 
Oracle architecture ppt
Oracle architecture pptOracle architecture ppt
Oracle architecture ppt
 

Similar to Gdb tutorial-handout

gdb-tutorial.pdf
gdb-tutorial.pdfgdb-tutorial.pdf
gdb-tutorial.pdfligi14
 
Introduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debuggerIntroduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debuggerNaoto Ono
 
Writing mruby Debugger
Writing mruby DebuggerWriting mruby Debugger
Writing mruby Debuggeryamanekko
 
GDB - a tough nut to crack: only a few bugs found by PVS-Studio
GDB - a tough nut to crack: only a few bugs found by PVS-StudioGDB - a tough nut to crack: only a few bugs found by PVS-Studio
GDB - a tough nut to crack: only a few bugs found by PVS-StudioPVS-Studio
 
CUDA by Example : Graphics Interoperability : Notes
CUDA by Example : Graphics Interoperability : NotesCUDA by Example : Graphics Interoperability : Notes
CUDA by Example : Graphics Interoperability : NotesSubhajit Sahu
 
Debugging of (C)Python applications
Debugging of (C)Python applicationsDebugging of (C)Python applications
Debugging of (C)Python applicationsRoman Podoliaka
 
Uwaga na buga! GDB w służbie programisty. Barcamp Semihalf S09:E01
Uwaga na buga! GDB w służbie programisty.  Barcamp Semihalf S09:E01Uwaga na buga! GDB w służbie programisty.  Barcamp Semihalf S09:E01
Uwaga na buga! GDB w służbie programisty. Barcamp Semihalf S09:E01Semihalf
 
Klement_0902_v2F (complete article)
Klement_0902_v2F (complete article)Klement_0902_v2F (complete article)
Klement_0902_v2F (complete article)Mike Friehauf
 
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming IComputer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I💻 Anton Gerdelan
 

Similar to Gdb tutorial-handout (20)

gdb-tutorial.pdf
gdb-tutorial.pdfgdb-tutorial.pdf
gdb-tutorial.pdf
 
GNU Debugger
GNU DebuggerGNU Debugger
GNU Debugger
 
Wavedigitech gdb
Wavedigitech gdbWavedigitech gdb
Wavedigitech gdb
 
gdb.ppt
gdb.pptgdb.ppt
gdb.ppt
 
lab1-ppt.pdf
lab1-ppt.pdflab1-ppt.pdf
lab1-ppt.pdf
 
Debuging like a pro
Debuging like a proDebuging like a pro
Debuging like a pro
 
Introduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debuggerIntroduction of Tools for providing rich user experience in debugger
Introduction of Tools for providing rich user experience in debugger
 
Writing mruby Debugger
Writing mruby DebuggerWriting mruby Debugger
Writing mruby Debugger
 
GDB - a tough nut to crack: only a few bugs found by PVS-Studio
GDB - a tough nut to crack: only a few bugs found by PVS-StudioGDB - a tough nut to crack: only a few bugs found by PVS-Studio
GDB - a tough nut to crack: only a few bugs found by PVS-Studio
 
CUDA by Example : Graphics Interoperability : Notes
CUDA by Example : Graphics Interoperability : NotesCUDA by Example : Graphics Interoperability : Notes
CUDA by Example : Graphics Interoperability : Notes
 
GDB tutorial
GDB tutorialGDB tutorial
GDB tutorial
 
02 c++g3 d (1)
02 c++g3 d (1)02 c++g3 d (1)
02 c++g3 d (1)
 
Debugging of (C)Python applications
Debugging of (C)Python applicationsDebugging of (C)Python applications
Debugging of (C)Python applications
 
Uwaga na buga! GDB w służbie programisty. Barcamp Semihalf S09:E01
Uwaga na buga! GDB w służbie programisty.  Barcamp Semihalf S09:E01Uwaga na buga! GDB w służbie programisty.  Barcamp Semihalf S09:E01
Uwaga na buga! GDB w służbie programisty. Barcamp Semihalf S09:E01
 
Klement_0902_v2F (complete article)
Klement_0902_v2F (complete article)Klement_0902_v2F (complete article)
Klement_0902_v2F (complete article)
 
MSL2009. Gdb
MSL2009. GdbMSL2009. Gdb
MSL2009. Gdb
 
Why Gradle?
Why Gradle?Why Gradle?
Why Gradle?
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
 
Computer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming IComputer Graphics - Lecture 01 - 3D Programming I
Computer Graphics - Lecture 01 - 3D Programming I
 
05-Debug.pdf
05-Debug.pdf05-Debug.pdf
05-Debug.pdf
 

Recently uploaded

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

Gdb tutorial-handout

  • 1. GDB Tutorial A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 GDB Tutorial
  • 2. What is gdb? “GNU Debugger” A debugger for several languages, including C and C++ It allows you to inspect what the program is doing at a certain point during execution. Errors like segmentation faults may be easier to find with the help of gdb. http://sourceware.org/gdb/current/onlinedocs/gdb toc.html - online manual GDB Tutorial
  • 3. Additional step when compiling program Normally, you would compile a program like: gcc [flags] <source files> -o <output file> For example: gcc -Wall -Werror -ansi -pedantic-errors prog1.c -o prog1.x Now you add a -g option to enable built-in debugging support (which gdb needs): gcc [other flags] -g <source files> -o <output file> For example: gcc -Wall -Werror -ansi -pedantic-errors -g prog1.c -o prog1.x GDB Tutorial
  • 4. Starting up gdb Just try “gdb” or “gdb prog1.x.” You’ll get a prompt that looks like this: (gdb) If you didn’t specify a program to debug, you’ll have to load it in now: (gdb) file prog1.x Here, prog1.x is the program you want to load, and “file” is the command to load it. GDB Tutorial
  • 5. Before we go any further gdb has an interactive shell, much like the one you use as soon as you log into the linux grace machines. It can recall history with the arrow keys, auto-complete words (most of the time) with the TAB key, and has other nice features. Tip If you’re ever confused about a command or just want more information, use the “help” command, with or without an argument: (gdb) help [command] You should get a nice description and maybe some more useful tidbits. . . GDB Tutorial
  • 6. Running the program To run the program, just use: (gdb) run This runs the program. If it has no serious problems (i.e. the normal program didn’t get a segmentation fault, etc.), the program should run fine here too. If the program did have issues, then you (should) get some useful information like the line number where it crashed, and parameters to the function that caused the error: Program received signal SIGSEGV, Segmentation fault. 0x0000000000400524 in sum array region (arr=0x7fffc902a270, r1=2, c1=5, r2=4, c2=6) at sum-array-region2.c:12 GDB Tutorial
  • 7. So what if I have bugs? Okay, so you’ve run it successfully. But you don’t need gdb for that. What if the program isn’t working? Basic idea Chances are if this is the case, you don’t want to run the program without any stopping, breaking, etc. Otherwise, you’ll just rush past the error and never find the root of the issue. So, you’ll want to step through your code a bit at a time, until you arrive upon the error. This brings us to the next set of commands. . . GDB Tutorial
  • 8. Setting breakpoints Breakpoints can be used to stop the program run in the middle, at a designated point. The simplest way is the command “break.” This sets a breakpoint at a specified file-line pair: (gdb) break file1.c:6 This sets a breakpoint at line 6, of file1.c. Now, if the program ever reaches that location when running, the program will pause and prompt you for another command. Tip You can set as many breakpoints as you want, and the program should stop execution if it reaches any of them. GDB Tutorial
  • 9. More fun with breakpoints You can also tell gdb to break at a particular function. Suppose you have a function my func: int my func(int a, char *b); You can break anytime this function is called: (gdb) break my func GDB Tutorial
  • 10. Now what? Once you’ve set a breakpoint, you can try using the run command again. This time, it should stop where you tell it to (unless a fatal error occurs before reaching that point). You can proceed onto the next breakpoint by typing “continue” (Typing run again would restart the program from the beginning, which isn’t very useful.) (gdb) continue You can single-step (execute just the next line of code) by typing “step.” This gives you really fine-grained control over how the program proceeds. You can do this a lot... (gdb) step GDB Tutorial
  • 11. Now what? (even more!) Similar to “step,” the “next” command single-steps as well, except this one doesn’t execute each line of a sub-routine, it just treats it as one instruction. (gdb) next Tip Typing “step” or “next” a lot of times can be tedious. If you just press ENTER, gdb will repeat the same command you just gave it. You can do this a bunch of times. GDB Tutorial
  • 12. Querying other aspects of the program So far you’ve learned how to interrupt program flow at fixed, specified points, and how to continue stepping line-by-line. However, sooner or later you’re going to want to see things like the values of variables, etc. This might be useful in debugging. :) The print command prints the value of the variable specified, and print/x prints the value in hexadecimal: (gdb) print my var (gdb) print/x my var GDB Tutorial
  • 13. Setting watchpoints Whereas breakpoints interrupt the program at a particular line or function, watchpoints act on variables. They pause the program whenever a watched variable’s value is modified. For example, the following watch command: (gdb) watch my var Now, whenever my var’s value is modified, the program will interrupt and print out the old and new values. Tip You may wonder how gdb determines which variable named my var to watch if there is more than one declared in your program. The answer (perhaps unfortunately) is that it relies upon the variable’s scope, relative to where you are in the program at the time of the watch. This just means that you have to remember the tricky nuances of scope and extent :(. GDB Tutorial
  • 14. Example programs Some example files are found in ~/212public/gdb-examples/broken.c on the linux grace machines. Contains several functions that each should cause a segmentation fault. (Try commenting out calls to all but one in main()) The errors may be easy, but try using gdb to inspect the code. GDB Tutorial
  • 15. Other useful commands backtrace - produces a stack trace of the function calls that lead to a seg fault (should remind you of Java exceptions) where - same as backtrace; you can think of this version as working even when you’re still in the middle of the program finish - runs until the current function is finished delete - deletes a specified breakpoint info breakpoints - shows information about all declared breakpoints Look at sections 5 and 9 of the manual mentioned at the beginning of this tutorial to find other useful commands, or just try help. GDB Tutorial
  • 16. gdb with Emacs Emacs also has built-in support for gdb. To learn about it, go here: http://tedlab.mit.edu/~dr/gdbintro.html GDB Tutorial
  • 17. More about breakpoints Breakpoints by themselves may seem too tedious. You have to keep stepping, and stepping, and stepping. . . Basic idea Once we develop an idea for what the error could be (like dereferencing a NULL pointer, or going past the bounds of an array), we probably only care if such an event happens; we don’t want to break at each iteration regardless. So ideally, we’d like to condition on a particular requirement (or set of requirements). Using conditional breakpoints allow us to accomplish this goal. . . GDB Tutorial
  • 18. Conditional breakpoints Just like regular breakpoints, except that you get to specify some criterion that must be met for the breakpoint to trigger. We use the same break command as before: (gdb) break file1.c:6 if i >= ARRAYSIZE This command sets a breakpoint at line 6 of file file1.c, which triggers only if the variable i is greater than or equal to the size of the array (which probably is bad if line 6 does something like arr[i]). Conditional breakpoints can most likely avoid all the unnecessary stepping, etc. GDB Tutorial
  • 19. Fun with pointers Who doesn’t have fun with pointers? First, let’s assume we have the following structure defined: struct entry { int key; char *name; float price; long serial_number; }; Maybe this struct is used in some sort of hash table as part of a catalog for products, or something related. GDB Tutorial
  • 20. Using pointers with gdb I Now, let’s assume we’re in gdb, and are at some point in the execution after a line that looks like: struct entry * e1 = <something>; We can do a lot of stuff with pointer operations, just like we could in C. See the value (memory address) of the pointer: (gdb) print e1 See a particular field of the struct the pointer is referencing: (gdb) print e1->key (gdb) print e1->name (gdb) print e1->price (gdb) print e1->serial number GDB Tutorial
  • 21. Using pointers with gdb II You can also use the dereference (*) and dot (.) operators in place of the arrow operator (->): (gdb) print (*e1).key (gdb) print (*e1).name (gdb) print (*e1).price (gdb) print (*e1).serial number See the entire contents of the struct the pointer references (you can’t do this as easily in C!): (gdb) print *e1 You can also follow pointers iteratively, like in a linked list: (gdb) print list prt->next->next->next->data GDB Tutorial