ghborrmann
ghborrmann

Reputation: 101

How to debug a function with gdb

Using gdb, I can put a breakpoint anywhere a function is called, and step through the function evaluation. I can also evaluate a function with the print command. When stopped at any breakpoint, I would like to debug a specific function by stepping through its execution using different arguments. However, when I try to set a breakpoint at the function and give gdb a suitable print command, gdb objects with the message "The program being debugged stopped while in a function called by gdb. Evaluation of the expression containing the function MyClass::mysize(int,int) will be abandoned". Is there any way to accomplish this without restarting the program?

Upvotes: 1

Views: 1283

Answers (1)

Andrew
Andrew

Reputation: 4751

You managed to miss part of the message from GDB. Here is my sample program:

int
foo (int arg)
{
  return arg + 3;
}

int
main ()
{
  return foo (-3);
}

And here is my GDB session:

(gdb) start
Temporary breakpoint 1 at 0x401119: file eval.c, line 10.
Starting program: eval.x 

Temporary breakpoint 1, main () at eval.c:10
10    return foo (-3);
(gdb) break foo
Breakpoint 2 at 0x40110d: file eval.c, line 4.
(gdb) print foo (2)

Breakpoint 2, foo (arg=2) at eval.c:4
4     return arg + 3;
The program being debugged stopped while in a function called from GDB.
Evaluation of the expression containing the function
(foo) will be abandoned.
When the function is done executing, GDB will silently stop.
(gdb) bt
#0  foo (arg=2) at eval.c:4
#1  <function called from gdb>
#2  main () at eval.c:10
(gdb) 

Notice the last line of the message from GDB: When the function is done executing, GDB will silently stop. So GDB is still inside the called function with the arguments you passed. The can be seen in the backtrace with <function called from GDB>.

So you can continue stepping through the function to see how it behaves. What you don't get is the printing of the result when the function returns, GDB has lost track of the fact that this is what you wanted, so instead, when the function returns GDB will just drop you back to the prompt. What this means is that you should inspect the return value inside the function before it returns.

Upvotes: 1

Related Questions