电脑技术学习

跟踪 UNIX 应用程序的解决方案

dn001

  我们来看一个例子,假设一个应用程序根据人的生日计算他的年龄,还要考虑到闰年等因素。要想调试这个应用程序,需要有源代码,还需要在启用调试选项的情况下编译应用程序:$ gcc -g ageindays.c -o ageindays。

  运行这个应用程序,提供用户的生日和用来比较的目标日期(见清单 1)。

  清单 1. 执行比较

$ ./ageindays 24/1/1980 22/2/2009 
You have been alive 10622 days 
You were born on 24/1/1980 which is a Thursday 

  在调试应用程序时,首先怀疑问题出在 calc_diff 函数中,这个函数计算第一个和第二个日期的差。接下来,可能按照清单 2 这样进行调试。

  清单 2. 调试 calc_diff 函数

$ gdb ageindays 
GNU gdb 6.3.50-20050815 (Apple version gdb-962) (Sat Jul 26 08:14:40 UTC 2008) 
Copyright 2004 Free Software Foundation, Inc. 
GDB is free software, covered by the GNU General Public License, and you are 
welcome to change it and/or distribute copIEs of it under certain conditions. 
Type "show copying" to see the conditions. 
There is absolutely no warranty for GDB. Type "show warranty" for details. 
This GDB was configured as "i386-apple-darwin"...Reading symbols for shared 
libraries ... done 
 
(gdb) b calc_diff 
Breakpoint 1 at 0x1bd7: file ageindays.c, line 27. 
(gdb) r 24/1/1980 26/3/2009 
Starting program: /nfs/MC/UnixSrc/c/bio/ageindays 24/1/1980 26/3/2009 
Reading symbols for shared libraries ++. done 
 
Breakpoint 1, calc_diff (day=26, month=3, year=2009) at ageindays.c:27 
27  unsigned long days_diff=0; 
(gdb) bt 
#0 calc_diff (day=26, month=3, year=2009) at ageindays.c:27 
#1 0x00001e3d in main (argc=3, argv=0xbffff708) at ageindays.c:89 
(gdb) p days_diff 
$1 = 8041 
(gdb) 

标签: