用gdb調試程序(Linux環境)

通常來講,GDB主要幫忙你完成下面四個方面的功能:app

    一、啓動你的程序,能夠按照你的自定義的要求爲所欲爲的運行程序。
    二、可以讓被調試的程序在你所指定的調置的斷點處停住。(斷點能夠是條件表達式)
    三、當程序被停住時,能夠檢查此時你的程序中所發生的事。
    四、動態的改變你程序的執行環境。
函數

  GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:spa

(參考:Debugging with GDB https://sourceware.org/gdb/current/onlinedocs/gdb/debug

  • Start your program, specifying anything that might affect its behavior.
  • Make your program stop on specified conditions.
  • Examine what has happened, when your program has stopped.
  • Change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another.

 一個調試示例:調試

一、源程序:tst.ccode

 1 #include <stdio.h>
 2 
 3 int func(int n)
 4 {
 5     int sum=0,i;
 6     for(i=0; i<n; i++)
 7     {
 8         sum+=i;
 9     }
10     return sum;
11 }
12 
13 
14 int main()
15 {
16     int i;
17     long result = 0;
18     for(i=1; i<=100; i++)
19     {
20         result += i;
21     }
22 
23     printf("result[1-100] = %ld /n", result );
24     printf("result[1-250] = %d /n", func(250) );
25 }

二、 編譯生成執行文件:#gcc -g tst.c -o tstblog

三、啓用GDB調試程序ci

四、#gdb tst                     //啓動gdb,進入gdb調試環境get

五、(gdb)list                     //list命令 從第一行開始列出源碼源碼

8            sum+=i;
9        }
10        return sum;
11    }
12    
13    
14    int main()
15    {
16        int i;
17        long result = 0;

六、(gdb)                         //直接回車,表示執行上一條命令

18        for(i=1; i<=100; i++)
19        {
20            result += i;
21        }
22    
23        printf("result[1-100] = %ld /n", result );
24        printf("result[1-250] = %d /n", func(250) );
25    }

七、(gdb)                         //直接回車,表示執行上一條命令

Line number 26 out of range; tst.c has 25 lines.

八、(gdb) break 16           //在源程序tst.c第16行設置斷點

Breakpoint 1 at 0x400563: file tst.c, line 16.

九、(gdb)break func          //在源程序中函數func()的入口處設置斷點,斷點在第5行

Breakpoint 2 at 0x400534: file tst.c, line 5.

十、(gdb)info break          //查看斷點信息

Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x0000000000400563 in main at tst.c:16
2       breakpoint     keep y   0x0000000000400534 in func at tst.c:5

十一、(gdb)r                       //輸入r,r是run命令的簡寫

Starting program: /root/c_study/tst 

Breakpoint 1, main () at tst.c:17
17        long result = 0;
Missing separate debuginfos, use: debuginfo-install glibc-2.17-196.el7_4.2.x86_64

十二、(gdb)n                     //輸入n,n是next命令的簡寫,next命令:執行下一條程序

18        for(i=1; i<=100; i++)

1三、(gdb)n

20            result += i;

1四、(gdb)n

18        for(i=1; i<=100; i++)

1五、(gdb)n

20            result += i;
相關文章
相關標籤/搜索