04 GDB

04 GDB

GDB调试命令

调试指令 shortcut 作 用 example
break xxx b 在源代码指定的某一行设置断点,其中 xxx 用于指定具体打断点的位置。 b 10
run r 执行被调试的程序,其会自动在第一个断点处暂停执行。 run
continue c 当程序在某一断点处停止运行后,使用该指令可以继续执行,直至遇到下一个断点或者程序结束。 c
next n 步过 n
print xxx p xxx 打印指定变量的值,其中 xxx 指的就是某一变量名。或者是一个表达式,或者是一个有副作用的函数。 p i
p i+100
p strcpy(name,“Jay”)
list l 显示源程序代码的内容,包括各行代码所在的行号。 list
quit q 终止调试。 q
set var 改变变量值 set var p=11
step s 单步执行 s
set args x x … 设置程序参数(特殊字符使用双引号包裹) set args hello 2

调试core文件

当程序挂掉,会产生一个core dump的错误,并生成一个core文件

1.查看core文件情况

$ ulimit -a	

core file size (blocks, -c) 0 #core文件默认不生成
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 7469
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 7469
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited

2.修改为无限制(unlimited)

ulimit -c unlimited

3.案例

3.1 挂掉的程序
//test.c
#include<stdio.h>
void bbb(int b)
{
int * c = 0;
*c = 100;
}

void aaa(int a)
{
bbb(a);
}

int main()
{
aaa(100);
return 0;
}

3.2 运行
gcc -g test.c -o test
./test

此时产生了一个core文件(core.xxxx)

3.3 使用gdb调试core文件
$ gdb test core-test-3218-1677370941

#显示错误
Reading symbols from test...
[New LWP 3218]
Core was generated by `./test'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x0000000000400549 in bbb (b=100) at t.c:5
5 *c = 100;
3.4 查看函数调用栈
(gdb) bt
#0 0x0000000000400549 in bbb (b=100) at t.c:5
#1 0x0000000000400567 in aaa (a=100) at t.c:10
#2 0x0000000000400578 in main () at t.c:15

4.其它:core文件不产生的问题

4.1 ulimit问题
ulimit -a	#查看
ulimit -c unlimited #更改
4.2 保存位置问题
cat /proc/sys/kernel/core_pattern	#查看保存位置
echo "core-%e-%p-%t" > /proc/sys/kernel/core_pattern #更改保存位置

#vim /etc/sysctl.conf
#添加一行:kernel.core_pattern=core-%e-%p-%t
echo "kernel.core_pattern=core-%e-%p-%t" >> /etc/sysctl.conf #使永久生效

sysctl -p #让配置立刻生效

作业

  • 安装gdb(windows+linux)

  • 尝试试用gdb的命令调试程序(python上面pdb)

  • 自己创造一个core dump,并能通过gdb找到原因