Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a variable on a particular condition in gdb?

Tags:

c

debugging

gdb

I wish to print the variable in a function (which is called multiple times ) to be printed each time the function is invoked.

Is it possible to do this automatically through gdb ?? Something like conditional printing ...

something like ..

void func()
{ 
    if( t == 0 ) 
       x = z+1;
    else
       x = p+2; 
} 

I want the variable to be printed when t == 0 and ignore otherwise ..

like image 313
Onkar Mahajan Avatar asked Nov 27 '10 03:11

Onkar Mahajan


People also ask

How do I apply a conditional breakpoint in gdb?

Use conditional breakpoints to conditionally stop program execution. Breakpoints normally stop the execution every time a certain line or function is reached. However, using the condition keyword, a breakpoint will only be activated if a certain condition is true.

What is print command in gdb?

The usual way to examine data in your program is with the print command (abbreviated p ), or its synonym inspect . It evaluates and prints the value of an expression of the language your program is written in (see section Using GDB with Different Languages).

How do I set variables in gdb?

Use the set variable (gdb) and the assign (dbx) commands to change the value associated with a variable, memory address, or expression that is accessible according to the scope and visibility rules of the language. The expression can be any expression that is valid in the current context.

Which command in gdb is used to find the type of variable?

The ptype [ARG] command will print the type. Show activity on this post.


1 Answers

This can be done with a combination of the commands breakpoint, condition, and commands.

  1. Set a breakpoint with breakpoint func
  2. Make it conditional by condition t == 0
  3. Make the breakpoint print local variables with:

.

commands  
info locals  
end  

or specific variables with:

commands  
print t
print z
print x  
end  
like image 68
wnoise Avatar answered Oct 06 '22 01:10

wnoise