#include<stdio.h> intfunc(int n) { int sum = 0, i; for (i = 0; i < n; ++i) { sum += i; } return sum; }
intmain() { int i; long result = 0; for (int i = 0; i < 100; ++i) { result += i; } printf("result[1-100] = %d /n", result); printf("result[1-250] = %d /n", func(250)); }
linux:~/$ gdb test1 <---------- 启动GDB GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2) 7.4-2012.04 Copyright (C) 2012 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty"for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://bugs.launchpad.net/gdb-linaro/>... Reading symbols from /home/linux/OSTEP/Homework/14.第十四章-插叙_内存操作api/code/test1...done. (gdb) l <-------------------- l命令相当于list,从第一行开始例出原码。 4 int sum = 0, i; 5 for (i = 0; i < n; ++i) { 6 sum += i; 7 } 8 returnsum; 9 } 10 11 int main() { 12 int i; 13 long result = 0; (gdb) <-------------------- 直接回车表示,重复上一次命令 14 for (i = 0; i < 100; ++i) { 15 result += i; 16 } 17 printf("result[1-100] = %d /n", (int)result); 18 printf("result[1-250] = %d /n", func(250)); 19 return 0; 20 } (gdb) break 12 <-------------------- 设置断点,在源程序第12行处。 Breakpoint 1 at 0x804841a: file test1.c, line 12. (gdb) break func <-------------------- 设置断点,在函数func()入口处。 Breakpoint 2 at 0x80483ea: file test1.c, line 4. (gdb) info break <-------------------- 查看断点信息。 Num Type Disp Enb Address What 1 breakpoint keep y 0x0804841a in main at test1.c:12 2 breakpoint keep y 0x080483ea in func at test1.c:4 (gdb) r <--------------------- 运行程序,run命令简写 Starting program: /home/linux/OSTEP/Homework/14.第十四章-插叙_内存操作api/code/test1
Breakpoint 1, main () at test1.c:13 <---------- 在断点处停住。 13 long result = 0; (gdb) n <--------------------- 单条语句执行,next命令简写。 14 for (i = 0; i < 100; ++i) { (gdb) n 15 result += i; (gdb) 14 for (i = 0; i < 100; ++i) { (gdb) 15 result += i; (gdb) c <--------------------- 继续运行程序,continue命令简写。 Continuing.
Breakpoint 2, func (n=250) at test1.c:4 4 int sum = 0, i; (gdb) n 5 for (i = 0; i < n; ++i) { (gdb) p i <--------------------- 打印变量i的值,print命令简写。 $1 = -1207961320 (gdb) n 6 sum += i; (gdb) n 5 for (i = 0; i < n; ++i) { (gdb) p i $2 = 0 (gdb) n 6 sum += i; (gdb) n 5 for (i = 0; i < n; ++i) { (gdb) p sum $3 = 1 (gdb) p i $4 = 1 (gdb) bt <--------------------- 查看函数堆栈。 #0 func (n=250) at test1.c:5 #1 0x08048461 in main () at test1.c:18 (gdb) finish <--------------------- 退出函数。 Run till exit from #0 func (n=250) at test1.c:5 0x08048461 in main () at test1.c:18 18 printf("result[1-250] = %d /n", func(250)); Value returned is $5 = 31125 (gdb) n 19 return 0; (gdb) c <--------------------- 继续运行。 Continuing. result[1-100] = 4950 /nresult[1-250] = 31125 /n[Inferior 1 (process 3516) exited normally] <----程序输出。程序退出,调试结束。 (gdb) q <--------------------- 退出gdb。 linux:~/$