如何在gdb中查看函数帧堆栈

how to view function frame stack in gdb

我是 c 和 gdb 的新手。我有一段带有递归函数的代码,所以我认为函数调用堆栈会在堆栈中累积。无论如何我可以使用gdb查看它吗?我尝试 google 一些 gdb 命令,但无法弄清楚如何正确使用它来查看函数调用堆栈。有人可以建议如何用 gdb 做吗?这是我的代码:

#include <stdlib.h>
#include <stdio.h>

int proc(int *a, int n) {
    if(n == 0) {
    return 0;
    } else {
    printf("%0d \n", a[n-1]);
    return proc(a , n-1) + a[n-1];  
    }
};


int main (int argc, char** argv) {
    int arrsize = 4;
    int *b = malloc(7*sizeof(int));
    b[0] = 7;
    b[1] = 6;
    b[2] = 5;
    b[3] = 3;
    b[4] = 2;
    b[5] = -4;
    b[6] = -5;
    proc(b, 4); // so I call this recursive function with n = 4, so I guess there should be 4 recursive calls. I just want to see in memory how the call is being built up. 

};



将您的测试程序放入 /tmp/test.c,然后:

$ gcc -g3 -O0 -o test.x test.c
$ gdb -q test.x
Reading symbols from test.x...
(gdb) b proc
Breakpoint 1 at 0x401145: file test.c, line 5.
(gdb) r
Starting program: /tmp/test.x 

Breakpoint 1, proc (a=0x4052a0, n=4) at test.c:5
5       if(n == 0) {
(gdb) bt
#0  proc (a=0x4052a0, n=4) at test.c:5
#1  0x000000000040123b in main (argc=1, argv=0x7fffffffb118) at test.c:24
(gdb) c
Continuing.
3 

Breakpoint 1, proc (a=0x4052a0, n=3) at test.c:5
5       if(n == 0) {
(gdb) bt
#0  proc (a=0x4052a0, n=3) at test.c:5
#1  0x000000000040118d in proc (a=0x4052a0, n=4) at test.c:9
#2  0x000000000040123b in main (argc=1, argv=0x7fffffffb118) at test.c:24
(gdb) c
Continuing.
5 

Breakpoint 1, proc (a=0x4052a0, n=2) at test.c:5
5       if(n == 0) {
(gdb) bt
#0  proc (a=0x4052a0, n=2) at test.c:5
#1  0x000000000040118d in proc (a=0x4052a0, n=3) at test.c:9
#2  0x000000000040118d in proc (a=0x4052a0, n=4) at test.c:9
#3  0x000000000040123b in main (argc=1, argv=0x7fffffffb118) at test.c:24
(gdb) c
Continuing.
6 

Breakpoint 1, proc (a=0x4052a0, n=1) at test.c:5
5       if(n == 0) {
(gdb) bt
#0  proc (a=0x4052a0, n=1) at test.c:5
#1  0x000000000040118d in proc (a=0x4052a0, n=2) at test.c:9
#2  0x000000000040118d in proc (a=0x4052a0, n=3) at test.c:9
#3  0x000000000040118d in proc (a=0x4052a0, n=4) at test.c:9
#4  0x000000000040123b in main (argc=1, argv=0x7fffffffb118) at test.c:24
(gdb) c
Continuing.
7 

Breakpoint 1, proc (a=0x4052a0, n=0) at test.c:5
5       if(n == 0) {
(gdb) bt
#0  proc (a=0x4052a0, n=0) at test.c:5
#1  0x000000000040118d in proc (a=0x4052a0, n=1) at test.c:9
#2  0x000000000040118d in proc (a=0x4052a0, n=2) at test.c:9
#3  0x000000000040118d in proc (a=0x4052a0, n=3) at test.c:9
#4  0x000000000040118d in proc (a=0x4052a0, n=4) at test.c:9
#5  0x000000000040123b in main (argc=1, argv=0x7fffffffb118) at test.c:24
(gdb) c
Continuing.
[Inferior 1 (process 3685291) exited normally]
(gdb) quit
$