【Linux】调试常见的应用程序奔溃“Segmentation fault (core dumped)”

您所在的位置:网站首页 linux如何产生core文件 【Linux】调试常见的应用程序奔溃“Segmentation fault (core dumped)”

【Linux】调试常见的应用程序奔溃“Segmentation fault (core dumped)”

2023-10-13 18:25| 来源: 网络整理| 查看: 265

文章目录 前言一、确保产生core文件二、利用core文件,调试确认terminated位置

前言

Linux程序开发者,日常遇到程序奔溃时,应该如何调试,如何寻找原因和解决呢?本文就介绍了遇到Segmentation fault (core dumped)问题时最常规的定位方法。

一、确保产生core文件

当你在命令行执行一个程序时,遇到Segmentation fault (core dumped)后,第一时间查看当前目录下是否产生了core-xxxxx文件。

如果没有产生core文件,以ubuntu20.0为例:

查询OS当前最core file size的配置: root@x-System-Product-Name:~# ulimit -a core file size (blocks, -c) unlimited data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 62634 max locked memory (kbytes, -l) 65536 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) 62634 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited

如果上图结果中的core file size是0,则需要进行步骤2设置。否则略过步骤2。

放开core file size(非永久生效) ulimit -c unlimited 设置core文件名格式 echo "core-%e-%p-%t" > /proc/sys/kernel/core_pattern 禁用OS自带的apport服务(ubuntu专有) sudo systemctl disable apport.service 运行你的程序,比如: ./build/example/testing 二、利用core文件,调试确认terminated位置 root@Name:/home# gdb build/examples/testing core-testing-1119167-1680772401 GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2 Copyright (C) 2020 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later 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 configuration" for configuration details. For bug reporting instructions, please see: . Find the GDB manual and other documentation resources online at: . For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from build/examples/testing... [New LWP 1119167] [New LWP 1119250] [New LWP 1119251] [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Core was generated by `./build/examples/testing'. Program terminated with signal SIGSEGV, Segmentation fault. #0 printf (__fmt=0x564c2c7d48e0 "data miscompare! lba[%lu]. rmt data[%xh]. local data[%xh]\n") at /usr/include/x86_64-linux-gnu/bits/stdio2.h:107 107 return __printf_chk (__USE_FORTIFY_LEVEL - 1, __fmt, __va_arg_pack ()); [Current thread is 1 (Thread 0x7f89a7611980 (LWP 1119167))] (gdb) Quit

由上图,一目了然,程序奔溃在一行printf语句。另外可以还可以敲bt查看调用栈!你学会了吗?

附上gdb常用方法

l(list) ,显示源代码,并且可以看到对应的行号; b(break)x, x是行号,表示在对应的行号位置设置断点; p(print)x, x是变量名,表示打印变量x的值 r(run), 表示继续执行到断点的位置 n(next),表示执行下一步 c(continue),表示继续执行 q(quit),表示退出gdb 启动gdb,注意该程序编译需要-g选项进行。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3