Example: dental hygienist

GDB Tutorial - A Walkthrough with Examples

GDB TutorialA Walkthrough with ExamplesCMSC 212 - Spring 2009 Last modified March 22, 2009 GDB TutorialWhat isgdb? GNU Debugger A debugger for several languages, includingCandC++It allows you to inspect what the program is doing at a certainpoint during likesegmentation faultsmay be easier to find with thehelp manualGDB TutorialAdditional step when compiling programNormally, you would compile a program like:gcc [flags] <source files> -o <output file>For example:gcc -Wall -Werror -ansi -pedantic-errors -o you add a-goption to enable built-in debugging support(whichgdbneeds):gcc [other flags]-g<source files> -o <output file>For example:gcc -Wall -Werror -ansi -o TutorialStarting upgdbJust try gdb or You ll get a prompt that lookslike this.

Mar 22, 2009 · GDB Tutorial A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 GDB Tutorial

Tags:

  Tutorials

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of GDB Tutorial - A Walkthrough with Examples

1 GDB TutorialA Walkthrough with ExamplesCMSC 212 - Spring 2009 Last modified March 22, 2009 GDB TutorialWhat isgdb? GNU Debugger A debugger for several languages, includingCandC++It allows you to inspect what the program is doing at a certainpoint during likesegmentation faultsmay be easier to find with thehelp manualGDB TutorialAdditional step when compiling programNormally, you would compile a program like:gcc [flags] <source files> -o <output file>For example:gcc -Wall -Werror -ansi -pedantic-errors -o you add a-goption to enable built-in debugging support(whichgdbneeds):gcc [other flags]-g<source files> -o <output file>For example:gcc -Wall -Werror -ansi -o TutorialStarting upgdbJust try gdb or You ll get a prompt that lookslike this.

2 (gdb)If you didn t specify a program to debug, you ll have to load it innow:(gdb) , the program you want to load, and file is thecommand to load TutorialBefore we go any furthergdbhas an interactive shell, much like the one you use as soon asyou log into the linux grace machines. It can recall history with thearrow keys, auto-complete words (most of the time) with the TABkey, and has other nice you re ever confused about a command or just want moreinformation, use the help command, with or without anargument:(gdb) help[command]You should get a nice description and maybe some more usefultidbits..GDB TutorialRunning the programTo run the program, just use:(gdb) runThis runs the it has no serious problems ( the normal program didn tget a segmentation fault, etc.)

3 , the program should run finehere the programdidhave issues, then you (should) get someuseful information like the line number where it crashed, andparameters to the function that caused the error:Program received signal SIGSEGV, Segmentation in sumarrayregion (arr=0x7fffc902a270, r1=2, c1=5,r2=4, c2=6) at :12 GDB TutorialSo what if I have bugs?Okay, so you ve run it successfully. But you don t needgdbforthat. What if the programisn tworking?Basic ideaChances are if this is the case, you don t want to run the programwithout any stopping, breaking, etc. Otherwise, you ll just rush past theerror and never find the root of the issue. So, you ll want tostep throughyour code a bit at a time, until you arrive upon the brings us to the next set of commands.

4 GDB TutorialSetting breakpointsBreakpoints can be used to stop the program run in the middle, ata designated point. The simplest way is the command break. This sets a breakpoint at a specified file-line pair:(gdb) :6 This sets a breakpoint atline6, Now,ifthe programever reaches that location when running, the program will pauseand prompt you for another can set as many breakpoints as you want, and the programshould stop execution if it reaches any of TutorialMore fun with breakpointsYou can also tellgdbto break at a particular function. Supposeyou have a functionmyfunc:int myfunc(int a, char *b);You can break anytime this function is called:(gdb) breakmyfuncGDB TutorialNow what?

5 Once you ve set a breakpoint, you can try using theruncommand 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 (Typingrunagain would restart the programfrom the beginning, which isn t very useful.)(gdb) continueYou can single-step (executejustthe next line of code) bytyping step. This gives you really fine-grained control overhow the program proceeds. You can do this (gdb) stepGDB TutorialNow 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, itjust treats it as one instruction.

6 (gdb) nextTipTyping step or next a lot of times can be tedious. If you justpress ENTER,gdbwill repeat the same command you just gave can do this a bunch of TutorialQuerying other aspects of the programSo far you ve learned how to interrupt program flow at fixed,specified points, and how to continue stepping , sooner or later you re going to want to see thingslikethe values of variables, etc. Thismightbe useful indebugging. :)Theprintcommand prints the value of the variablespecified, andprint/xprints the value in hexadecimal:(gdb) printmyvar(gdb) print/xmyvarGDB TutorialSetting watchpointsWhereas breakpoints interrupt the program at a particular line orfunction, watchpoints act on variables.

7 They pause the programwhenever awatchedvariable s value is modified. For example, thefollowingwatchcommand:(gdb) watchmyvarNow, whenevermyvar s value is modified, the program willinterrupt and print out the old and new may wonder howgdbdetermines which variable namedmyvartowatchif thereis more than one declared in your program. The answer (perhaps unfortunately) isthat it relies upon the variable sscope, relative to where you are in the program at thetime of the watch. This just means that you have to remember the tricky nuances ofscope and extent :(.GDB TutorialExample programsSome example files are found in~/212public/gdb- the linux several functions that each should cause asegmentation fault.)

8 (Try commenting out calls to all but oneinmain())The errors may be easy, but try usinggdbto inspect the TutorialOther useful commandsbacktrace- produces a stack trace of the function calls thatlead to a seg fault (should remind you of Java exceptions)where- same asbacktrace; you can think of this version asworking even when you re still in the middle of the programfinish- runs until the current function is finisheddelete- deletes a specified breakpointinfo breakpoints- shows information about all declaredbreakpointsLook at sections 5 and 9 of the manual mentioned at the beginningof this Tutorial to find other useful commands, or just Tutorialgdbwith EmacsEmacs also has built-in support forgdb.

9 To learn about it, go here: ~ TutorialMore about breakpointsBreakpoints by themselves may seem too tedious. You have tokeep stepping, and stepping, and stepping..Basic ideaOnce we develop an idea for what the error could be (like dereferencing aNULL pointer, or going past the bounds of an array), we probably onlycare if such an event happens; we don t want to break at each ideally, we d like toconditionon a particular requirement (or setof requirements). Usingconditionalbreakpoints allow us toaccomplish this goal..GDB TutorialConditional breakpointsJust like regular breakpoints, except that you get to specify somecriterion that must be met for the breakpoint to trigger.

10 We usethe samebreakcommand as before:(gdb) break :6if i >= ARRAYSIZEThis command sets a breakpoint at line 6 of , whichtriggersonly if the variableiis greater than or equal to the size ofthe array(which probably is bad if line 6 does something likearr[i]). Conditional breakpoints can most likely avoid all theunnecessary stepping, TutorialFun with pointersWhodoesn thave fun with pointers? First, let s assume we havethe 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 acatalog for products, or something TutorialUsing pointers withgdbINow, let s assume we re ingdb, and are at some point in the executionafter a line that looks like:struct entry * e1 = <something>.


Related search queries