GDB (Step by Step Introduction) - GeeksforGeeks (2024)

Last Updated : 12 Jul, 2024

Improve

GDB stands for GNU Project Debugger and is a powerful debugging tool for C (along with other languages like C++). It helps you to poke around inside your C programs while they are executing and also allows you to see what exactly happens when your program crashes. GDB operates on executable files which are binary files produced by the compilation process.

For demo purposes, the example below is executed on a Linux machine with the below specs.

uname -a

GDB (Step by Step Introduction) - GeeksforGeeks (1)

uname -a

Let’s learn by doing: –

Start GDB

Go to your Linux command prompt and type “gdb”.

gdb

GDB (Step by Step Introduction) - GeeksforGeeks (2)

gdb

Gdb open prompt lets you know that it is ready for commands. To exit out of gdb, type quit or q.

GDB (Step by Step Introduction) - GeeksforGeeks (3)

To quit

Compile the code

Below is a program that shows undefined behavior when compiled using C99. GDB (Step by Step Introduction) - GeeksforGeeks (4)

Note: If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate, where the indeterminate value is either an unspecified value or a trap representation.

Now compile the code. (here test.c). g flag means you can see the proper names of variables and functions in your stack frames, get line numbers and see the source as you step around in the executable. -std=C99 flag implies use standard C99 to compile the code. -o flag writes the build output to an output file.

gcc -std=c99 -g -o test test.C

GDB (Step by Step Introduction) - GeeksforGeeks (5)

gcc -std=c99 -g -o test test.C

Run GDB with the generated executable

Type the following command to start GDB with the compiled executable.

gdb ./test

GDB (Step by Step Introduction) - GeeksforGeeks (6)

gdb ./test

Useful GDB commands:

Here are a few useful commands to get started with GDB.

CommandDescription
run or rExecutes the program from start to end.
break or bSets a breakpoint on a particular line.
disableDisables a breakpoint
enableEnables a disabled breakpoint.
next or nExecutes the next line of code without diving into functions.
stepGoes to the next instruction, diving into the function.
list or lDisplays the code.
print or pDisplays the value of a variable.
quit or qExits out of GDB.
clearClears all breakpoints.
continueContinues normal execution

Display the code

Now, type “l” at gdb prompt to display the code.

GDB (Step by Step Introduction) - GeeksforGeeks (7)

Display the code

Set a breakpoint

Let’s introduce a break point, say line 5.

GDB (Step by Step Introduction) - GeeksforGeeks (8)

Set a breakpoint

If you want to put breakpoint at different lines, you can type “b line_number“.By default “list or l” display only first 10 lines.

View breakpoints

In order to see the breakpoints, type “info b”.

GDB (Step by Step Introduction) - GeeksforGeeks (9)

View breakpoints

Disable a breakpoint

Having done the above, let’s say you changed your mind and you want to revert. Type “disable b”.

GDB (Step by Step Introduction) - GeeksforGeeks (10)

Disable a breakpoint

Re-enable a disabled breakpoint

As marked in the blue circle, Enb becomes n for disabled. 9. To re-enable the recent disabled breakpoint. Type “enable b”.

GDB (Step by Step Introduction) - GeeksforGeeks (11)

Re-enable a disabled breakpoint

Run the code

Run the code by typing “run or r”.If you haven’t set any breakpoints, the run command will simply execute the full program.

GDB (Step by Step Introduction) - GeeksforGeeks (12)

Run the code

Print variable values

To see the value of variable, type “print variable_name or p variable_name“.

GDB (Step by Step Introduction) - GeeksforGeeks (13)

Print variable values

The above shows the values stored at x at time of execution.

Change variable values

To change the value of variable in gdb and continue execution with changed value, type “set variable_name“.

Debugging output

Below screenshot shows the values of variables from which it’s quite understandable the reason why we got a garbage value as output. At every execution of ./test we will be receiving a different output.

Exercise: Try using set x = 0 in gdb at first run and see the output of c.

GDB (Step by Step Introduction) - GeeksforGeeks (14)

Debugging output

GDB offers many more ways to debug and understand your code like examining stack, memory, threads, manipulating the program, etc. I hope the above example helps you get started with gdb.

Conclusion

In this article we have discussed GDB (GNU Debugger) which is a powerful tool in Linux used for debugging C programs. We have discussed some of the following steps so that we can compile your code with debugging information, run GDB, set breakpoint, examine variables, and analyze program behavior. We have also discussed GDB’s features, such as code examination, breakpoint management, variable manipulation, and program execution control which allow us to efficiently debug and issue resolution.

GDB (Step by Step Introduction) – FAQs

How to go step by step in GDB?

To step through a program in GDB, you can use the following commands:

  • step (or s): Step into functions.
  • next (or n): Step over functions.
  • continue (or c): Continue execution until the next breakpoint.

Example:

gdb ./myprogram
(gdb) break main
(gdb) run
(gdb) step
(gdb) next

What is the overview of GDB?

GDB (GNU Debugger) is a powerful debugging tool for C, C++, and other programming languages. It allows developers to see what is happening inside their programs while they are running or what the program was doing at the moment it crashed. GDB provides features like breakpoints, stepping through code, inspecting variables, and changing program execution flow.

How to start a process in GDB?

To start a process in GDB, follow these steps:

  1. Compile your program with the -g flag to include debugging information.
  2. Start GDB with your program.
  3. Run the program inside GDB.
gcc -g -o myprogram myprogram.c
gdb ./myprogram
(gdb) run

How to program with GDB?

To debug a program with GDB:

  1. Compile the program with debugging information.
  2. Start GDB.
  3. Set breakpoints, run the program, and use debugging commands.
gcc -g -o myprogram myprogram.c
gdb ./myprogram
(gdb) break main
(gdb) run
(gdb) step
(gdb) next
(gdb) print variable

How to generate core file in GDB?

To generate a core file in GDB:

  1. Enable core dumps in your shell session.
  2. Run your program until it crashes.
  3. A core file (core or core.<pid>) will be generated in the current directory.
  4. Load the core file into GDB for analysis.
ulimit -c unlimited
./myprogram
gdb ./myprogram core


T

thelittleguy046

Improve

Next Article

The Ultimate Beginner's Guide For DSA

Please Login to comment...

GDB (Step by Step Introduction) - GeeksforGeeks (2024)

FAQs

What is GDB in Linux? ›

GDB stands for the “Gnu DeBugger.” This is a powerful source-level debugging package that lets you see what is going on inside your program. You can step through the code, set breakpoints, examine and change variables, and so on. Like most Linux tools, GDB itself is command line driven, making it rather tedious to use.

How to use GDB breakpoints? ›

Setting breakpoints A breakpoint is like a stop sign in your code -- whenever gdb gets to a breakpoint it halts execution of your program and allows you to examine it. To set breakpoints, type "break [filename]:[linenumber]". For example, if you wanted to set a breakpoint at line 55 of main.

What is the introduction of GDB? ›

Gdb is a debugger for C (and C++). It allows you to do things like run the program up to a certain point then stop and print out the values of certain variables at that point, or step through the program one line at a time and print out the values of each variable after executing each line.

What is the difference between step and Stepi in GDB? ›

Use the step command to execute a line of source code. When the line being stepped contains a function call, the step command steps into the function and stops at the first executable statement. Use the stepi command to step into the next machine instruction.

How to run step by step? ›

Feet: Land with your foot centered and directly under your body. Body: Keep your upper body upright yet relaxed. As you run, lean slightly forward so you have better momentum. Avoid hunching over or bending from your hips.

Is GDB the best debugger? ›

In terms of usability, GDB is a versatile tool with strong debugging capabilities, and flexibility across multiple platforms and programming languages.

What language can GDB debug? ›

gdb supports C, C++, D, Objective-C, Fortran, Java, OpenCL C, Pascal, assembly, Modula-2, and Ada. Some gdb features may be used in expressions regardless of the language you use: the gdb @ and :: operators, and the ` {type}addr ' construct (see Expressions) can be used with the constructs of any supported language.

What is the difference between GDB and GDB server? ›

gdbserver is sometimes useful nevertheless, because it is a much smaller program than GDB itself. It is also easier to port than all of GDB, so you may be able to get started more quickly on a new system by using gdbserver .

Can you step backwards in GDB? ›

When you are debugging a program, it is not unusual to realize that you have gone too far, and some event of interest has already happened. If the target environment supports it, gdb can allow you to “rewind” the program by running it backward.

How do you exit GDB without killing process? ›

To exit GDB, use the quit command (abbreviated q ), or type an end-of-file character (usually C-d ). If you do not supply expression , GDB will terminate normally; otherwise it will terminate using the result of expression as the error code.

How do you stop execution in GDB? ›

An interrupt (often C-c ) does not exit from GDB, but rather terminates the action of any GDB command that is in progress and returns to GDB command level. It is safe to type the interrupt character at any time because GDB does not allow it to take effect until a time when it is safe.

What are the data types in GDB? ›

The integral datatypes used in the system calls are int , unsigned int , long , unsigned long , mode_t , and time_t . int , unsigned int , mode_t and time_t are implemented as 32 bit values in this protocol. long and unsigned long are implemented as 64 bit types.

How to remove breakpoint in GDB? ›

Deleting breakpoints

With the clear command you can delete breakpoints according to where they are in your program. With the delete command you can delete individual breakpoints, watchpoints, or catchpoints by specifying their breakpoint numbers. It is not necessary to delete a breakpoint to proceed past it.

How to program with GDB? ›

Starting your program. Use the run command to start your program under GDB. You must first specify the program name (except on VxWorks) with an argument to GDB (see section Getting In and Out of GDB), or by using the file or exec-file command (see section Commands to specify files).

How do I run a file in GDB? ›

Use the run command to start your program under GDB. You must first specify the program name (except on VxWorks) with an argument to GDB (see section Getting In and Out of GDB), or by using the file or exec-file command (see section Commands to specify files).

How do I debug a running process in GDB? ›

Procedure
  1. Start GDB attached to the application or library you want to debug. ...
  2. Exit GDB without proceeding further: type q and Enter . ...
  3. Run the command suggested by GDB to install the needed debuginfo packages: ...
  4. In case GDB is not able to suggest the debuginfo package, follow the procedure in Section 20.1.

How do I step out a function in GDB? ›

Those who use Visual Studio will be familiar with the Shift + F11 hotkey, which steps out of a function, meaning it continues execution of the current function until it returns to its caller, at which point it stops.

What is the difference between step and continue in GDB? ›

Continuing means resuming program execution until your program completes normally. In contrast, stepping means executing just one more "step" of your program, where "step" may mean either one line of source code, or one machine instruction (depending on what particular command you use).

Top Articles
Two Soyjaks Pointing Png
Koliva – Zitronen & Olivenöl
Sdn Md 2023-2024
Cappacuolo Pronunciation
CLI Book 3: Cisco Secure Firewall ASA VPN CLI Configuration Guide, 9.22 - General VPN Parameters [Cisco Secure Firewall ASA]
Ret Paladin Phase 2 Bis Wotlk
2024 Fantasy Baseball: Week 10 trade values chart and rest-of-season rankings for H2H and Rotisserie leagues
Ati Capstone Orientation Video Quiz
Localfedex.com
Cube Combination Wiki Roblox
Otr Cross Reference
FIX: Spacebar, Enter, or Backspace Not Working
Transformers Movie Wiki
Meritas Health Patient Portal
Becu Turbotax Discount Code
Houses and Apartments For Rent in Maastricht
Define Percosivism
Icommerce Agent
Paychex Pricing And Fees (2024 Guide)
2024 INFINITI Q50 Specs, Trims, Dimensions & Prices
The Tower and Major Arcana Tarot Combinations: What They Mean - Eclectic Witchcraft
Little Rock Skipthegames
Hannaford To-Go: Grocery Curbside Pickup
Ceramic tiles vs vitrified tiles: Which one should you choose? - Building And Interiors
Breckiehill Shower Cucumber
Foodsmart Jonesboro Ar Weekly Ad
Coindraw App
Stephanie Bowe Downey Ca
Eegees Gift Card Balance
Craigslist Sf Garage Sales
Broken Gphone X Tarkov
Haunted Mansion Showtimes Near Cinemark Tinseltown Usa And Imax
Boondock Eddie's Menu
Myhrconnect Kp
Muma Eric Rice San Mateo
THE 10 BEST Yoga Retreats in Konstanz for September 2024
Oreillys Federal And Evans
How to play Yahoo Fantasy Football | Yahoo Help - SLN24152
Lake Kingdom Moon 31
Dinar Detectives Cracking the Code of the Iraqi Dinar Market
Subdomain Finder
Vintage Stock Edmond Ok
Stosh's Kolaches Photos
Haunted Mansion (2023) | Rotten Tomatoes
Meet Robert Oppenheimer, the destroyer of worlds
Page 5747 – Christianity Today
The 5 Types of Intimacy Every Healthy Relationship Needs | All Points North
Fallout 76 Fox Locations
Uncle Pete's Wheeling Wv Menu
211475039
Shad Base Elevator
7 National Titles Forum
Latest Posts
Article information

Author: Delena Feil

Last Updated:

Views: 6446

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.