gdb笔记 ---《Linux.C编程一站式学习》
gdb笔记 ---《Linux.C编程一站式学习》
单步执行和跟踪函数调用
函数调试实例
#include <stdio.h>
int add_range(int low, int high)
{
int i, sum;
for (i = low; i <= high; i++)
{
sum = sum + i;
}
return sum;
}
int main(void)
{
int result[100];
result[0] = add_range(1, 10);
result[1] = add_range(1, 100);
printf("result[0] = %d\n result[1] = %d\n", result[0], result[1]);
return 0;
}
arrange_range函数从low加到high,程序打印的结果为:
<1>result[0] = 55
<2>result[1] = 5105
打印<1>结果正确,但<2>结果出错。<1>和<2>都是运行同一段代码,假如代码是错的,<1>却是正确的。
在阅读理解代码后还是找不出错误,可以使用gdb进行源码级的调试:
gdb进行源码级调试
编译时要加上-g的选项,生成可让gdb进行源码级调试的可执行文件。
-g选项作用:在可执行文件中加入源代码的信息,比如可执行文件中第几条机器指令对应源代码的第几行,在调试的时候确保gdb能找到源代码
没加-g选项:
$ gcc -g main.c -o main
$ gdb main
GNU gdb (Ubuntu 7.11-1-0ubuntu1~16.5) 7.11.1 //版本号
Copyright (C) 2016 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 "x86_64-linux-gnu".//设置
Type "show configured " for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources onlice at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "aprops word" to search for command for commands related to "word"...//查找命令
"/home/lyl/Desktop/main.c": not in executable format: File format not recongnized //不可执行的格式:文件格式不可识别
(gdb)
gdb的help命令
(gdb) help
List of classes of commands:
aliases -- Aliases of other commands //命令的别名
breakpoints -- Making program stop at certain points //断点:使程序停止在你需要停止的某些点上
data -- Examining data //检查数据
files -- Specifying and examining files //指定和检查文件
internals -- Maintenance commands //维护命令?翻译不知道是否正确
obscure -- Obscure features //提供编译,记录,监控等功能
running -- Running the program
stack -- Examing the stack //检查堆栈
status -- status inquireis //状态查询?
support -- Support facilities //支持的设备?
tracepoints -- Tracing of program execution whithout stopping the program //当程序没有停止的时候跟踪程序
user-defined -- 用户自定义命令
Type "help" followed by a class name for a list of commands i that class.
Type "help all" for the list of all commands.
Type "help" followed by command name for full documentation.
Type "apropos word" to search for commands related to "word".
Command name abbreviations are allowed if unmbiguous.
进一步查看某一类别有哪些命令
help files #help + 类别
list命令:从第一行开始列出源代码
(gdb) list 1
1 #include <stdio.h>
2
3 int add_range(int low, int high)
4 {
5 int i, sum;
6 for(i = low; i <= high; i++)
7 sum = sum + i;
8 return sum;
9 }
10
吾生也有涯,而知也无涯。