如何解决 “ 段错误(吐核) ” ??? 您所在的位置:网站首页 调试错误怎么解决 如何解决 “ 段错误(吐核) ” ???

如何解决 “ 段错误(吐核) ” ???

2023-09-22 22:41| 来源: 网络整理| 查看: 265

一、段错误的形式:       

在编程中以下几类做法容易导致段错误,基本上是错误地使用指针引起的。

1)访问系统数据区,尤其是往系统保护的内存地址写数据最常见就是给一个指针以0地址。

2)内存越界(数组越界,变量类型不一致等): 访问到不属于你的内存区域。

解决方法:我们在用C/C++语言写程序的时候,内存管理的绝大部分工作都是需要我们来做的。实际上,内存管理是一个比较繁琐的工作,无论你多高明,经验多丰富,难免会在此处犯些小错误,而通常这些错误又是那么的浅显而易于消除。但是手工“除虫”(debug),往往是效率低下且让人厌烦的,本文将就"段错误"这个内存访问越界的错误谈谈如何快速定位这些"段错误"的语句。

二、下面将就以下的一个存在段错误的程序介绍几种调试方法:

test的代码如下:

[root@localhost TEST]# cat test.c -n 1 #include 2 int main(void) 3 { 4 printf("111"); 5 printf("222"); 6 int *ptr = NULL; 7 *ptr = 1; 8 } 1)使用命令    gcc -g -rdynamic test.c 然后gdb调试 [root@localhost TEST]# gcc -g -rdynamic test.c

 1.1)查找段错误: 这种方法也是被大众所熟知并广泛采用的方法,首先我们需要一个带有调试信息的可执行程序,所以我们加上“-g -rdynamic"的参数进行编译,然后用gdb调试运行这个新编译的程序,具体步骤如下:

[root@localhost TEST]# gcc -g -rdynamic test.c [root@localhost TEST]# gdb ./a.out GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-80.el7 Copyright (C) 2013 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-redhat-linux-gnu". For bug reporting instructions, please see: ... Reading symbols from /root/桌面/TEST/a.out...done. (gdb) r Starting program: /root/桌面/TEST/./a.out Program received signal SIGSEGV, Segmentation fault. 0x00000000004007d2 in main () at test.c:7 7 *ptr = 1; Missing separate debuginfos, use: debuginfo-install glibc-2.17-105.el7.x86_64 (gdb)

不用一步步调试我们就找到了出错位置d.c文件的第4行,其实就是如此的简单。

从这里我们还发现进程是由于收到了SIGSEGV信号而结束的。通过进一步的查阅文档(man 7 signal),我们知道SIGSEGV默认handler的动作是打印”段错误"的出错信息,并产生Core文件,由此我们又产生了方法二。

2)使用命令   ulimit 命令

 1.1)查找段错误:

[root@localhost TEST]# ulimit -c 0 [root@localhost TEST]# ulimit -c 1000 [root@localhost TEST]# ./a.out 段错误(吐核) [root@localhost TEST]# ls a.out core.15180 test test.c [root@localhost TEST]# gdb ./a.out core.15180 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-80.el7 Copyright (C) 2013 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-redhat-linux-gnu". For bug reporting instructions, please see: ... Reading symbols from /root/桌面/TEST/a.out...done. [New LWP 15180] Core was generated by `./a.out'. Program terminated with signal 11, Segmentation fault. #0 0x00000000004007d2 in main () at test.c:7 7 *ptr = 1; Missing separate debuginfos, use: debuginfo-install glibc-2.17-105.el7.x86_64

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有