How to debug a Program with gdb – Part 2

The Previous article <How to debug a Program with gdb> described the use of running gdb on a sample program. In this article, we shall understand how to print variables, access memory and run a few gdb commands to access stack

gdb has a lot many commands and the interested reader can access the different gdb commands at the links provided below which i found very valuable

<GDB tutorialpoint>

<GDB GNU Site>

<GDB useful commands>

The sample program is given below

Compiling the program and loading the program via gdb

Let us place a break-point at function foo

to run the program, the below gdb command

when the run command is executed, it runs till the break point which is placed at function foo. Let us execute a few commands to check for variables and memory

print command – print (short form – p)

If we attempt to access the  variable “j” – we will get the below error. That is because, the program stack is currently in function foo. we can see the stack frame via the “backtrace” command

backtrace command – (short form -bt)

As can be seen from the back trace – the current stack frame is in function foo. If we attempt to access the variable “j” which is local to Function “main” – GDB will not be able to print it. To access a particular stack frame – a user can execute the “frame” command. It is shown below

frame command

As seen above – once we load the proper frame (frame 1 in this case)- we are able to access the variable “j”.

Some useful print commands , deleting break points, continuing execution of the program, to look at memory, to step into a function, to go to the next line of a function  are provided below

  1. to look at memory – ‘x’ command
  2. to step into a function – step command
  3. to continue execution – continue command
  4. to clear a break point – clear command

How To look at Core Files with GDB

 

 

Comments

  1. Pingback: How to debug a program with GDB | Hitch Hiker's Guide to Learning

Leave a Reply

Your email address will not be published. Required fields are marked *