GDB - get total number of frames on the call stack of the current thread

Viewed 197

When stopped at a breakpoint, does gdb have a command that prints how many frames are there on the call stack for the current thread?

Presently, I do bt to print the entire backtrace for the thread, and then count the number of frames manually. I am guessing gdb has a command to do this, I just could not find it.

1 Answers

You can give bt an argument of -1 to show just the bottommost frame (see GDB: Backtraces), then add 1 to the frame number (since the frames are numbered consecutively, starting at 0):

$ gdb fib2
...
(gdb) bt
#0  fib (n=4) at fib2.c:5
#1  0x0000000008000714 in fib (n=5) at fib2.c:7
#2  0x0000000008000714 in fib (n=6) at fib2.c:7
#3  0x0000000008000714 in fib (n=7) at fib2.c:7
#4  0x0000000008000714 in fib (n=8) at fib2.c:7
#5  0x0000000008000714 in fib (n=9) at fib2.c:7
#6  0x0000000008000757 in main () at fib2.c:15

(gdb) bt -1
#6  0x0000000008000757 in main () at fib2.c:15

Alternatively, if you want more customized output, here's how to do it using GDB's Python extensions (see GDB: Frames In Python):

$ cat framecount.py
def framecount():
  f = gdb.newest_frame()
  count = 0
  while f:
    count += 1
    f = f.older()
  print(count, "frames")

$ gdb fib2
...
(gdb) source framecount.py
(gdb) py framecount()
7 frames
Related