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

     1  dummy_function (void)
     2  {
     3          unsigned char *ptr = 0x00;
     4          *ptr = 0x00;
     5  }
     6
     7  int main (void)
     8  {
     9          dummy_function ();
    10
    11          return 0;
    12  }

作为一个熟练的C/C++程序员,以上代码的bug应该是很清楚的,因为它尝试操作地址为0的内存区域,而这个内存区域通常是不可访问的禁区,当然就会出错了。我们尝试编译运行它:

xiaosuo@gentux test $ ./a.out
段错误

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

xiaosuo@gentux test $ gcc -g -rdynamic d.c
xiaosuo@gentux test $ gdb ./a.out
GNU gdb 6.5
Copyright (C) 2006 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 "i686-pc-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1".

(gdb) r
Starting program: /home/xiaosuo/test/a.out

Program received signal SIGSEGV, Segmentation fault.
0x08048524 in dummy_function () at d.c:4
4               *ptr = 0x00;
(gdb)                       

哦?!好像不用一步步调试我们就找到了出错位置d.c文件的第4行,其实就是如此的简单。
从这里我们还发现进程是由于收到了SIGSEGV信号而结束的。通过进一步的查阅文档(man 7 signal),我们知道SIGSEGV默认handler的动作是打印”段错误"的出错信息,并产生Core文件,由此我们又产生了方法二。
2.分析Core文件: 
Core文件是什么呢?

The  default action of certain signals is to cause a process to terminate and produce a core dump file, a disk file containing an image of the process's memory  at the time of termination.  A list of the signals which cause a process to dump core can be found in signal(7).

以 上资料摘自man page(man 5 core)。不过奇怪了,我的系统上并没有找到core文件。后来,忆起为了渐少系统上的拉圾文件的数量(本人有些洁癖,这也是我喜欢Gentoo的原因 之一),禁止了core文件的生成,查看了以下果真如此,将系统的core文件的大小限制在512K大小,再试:

xiaosuo@gentux test $ ulimit -c
0
xiaosuo@gentux test $ ulimit -c 1000
xiaosuo@gentux test $ ulimit -c
1000
xiaosuo@gentux test $ ./a.out
段错误 (core dumped)
xiaosuo@gentux test $ ls
a.out  core  d.c  f.c  g.c  pango.c  test_iconv.c  test_regex.c

core文件终于产生了,用gdb调试一下看看吧:

xiaosuo@gentux test $ gdb ./a.out core
GNU gdb 6.5
Copyright (C) 2006 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 "i686-pc-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1".

warning: Can't read pathname for load map: 输入/输出错误.
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x08048524 in dummy_function () at d.c:4
4               *ptr = 0x00;

哇,好历害,还是一步就定位到了错误所在地,佩服一下Linux/Unix系统的此类设计。
接着考虑下去,以前用windows系统下的ie的时侯,有时打开某些网页,会出现“运行时错误”,这个时侯如果恰好你的机器上又装有windows的编译器的话,他会弹出来一个对话框,问你是否进行调试,如果你选择是,编译器将被打开,并进入调试状态,开始调试。
Linux下如何做到这些呢?我的大脑飞速地旋转着,有了,让它在SIGSEGV的handler中调用gdb,于是第三个方法又诞生了:
3.段错误时启动调试:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>

void dump(int signo)
{
        char buf[1024];
        char cmd[1024];
        FILE *fh;

snprintf(buf, sizeof(buf), "/proc/%d/cmdline", getpid());
        if(!(fh = fopen(buf, "r")))
                exit(0);
        if(!fgets(buf, sizeof(buf), fh))
                exit(0);
        fclose(fh);
        if(buf[strlen(buf) - 1] == '/n')
                buf[strlen(buf) - 1] = '/0';
        snprintf(cmd, sizeof(cmd), "gdb %s %d", buf, getpid());
        system(cmd);

exit(0);
}

void
dummy_function (void)
{
        unsigned char *ptr = 0x00;
        *ptr = 0x00;
}

int
main (void)
{
        signal(SIGSEGV, &dump);
        dummy_function ();

return 0;
}

编译运行效果如下:

xiaosuo@gentux test $ gcc -g -rdynamic f.c
xiaosuo@gentux test $ ./a.out
GNU gdb 6.5
Copyright (C) 2006 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 "i686-pc-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1".

Attaching to program: /home/xiaosuo/test/a.out, process 9563
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
0xffffe410 in __kernel_vsyscall ()
(gdb) bt
#0  0xffffe410 in __kernel_vsyscall ()
#1  0xb7ee4b53 in waitpid () from /lib/libc.so.6
#2  0xb7e925c9 in strtold_l () from /lib/libc.so.6
#3  0x08048830 in dump (signo=11) at f.c:22
#4  <signal handler called>
#5  0x0804884c in dummy_function () at f.c:31
#6  0x08048886 in main () at f.c:38

怎么样?是不是依旧很酷?
以上方法都是在系统上有gdb的前提下进行的,如果没有呢?其实glibc为我们提供了此类能够dump栈内容的函数簇,详见/usr/include/execinfo.h(这些函数都没有提供man page,难怪我们找不到),另外你也可以通过gnu的手册 进行学习。
4.利用backtrace和objdump进行分析: 
重写的代码如下:

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

/* A dummy function to make the backtrace more interesting. */
        void
dummy_function (void)
{
        unsigned char *ptr = 0x00;
        *ptr = 0x00;
}

void dump(int signo)
{
        void *array[10];
        size_t size;
        char **strings;
        size_t i;

size = backtrace (array, 10);
        strings = backtrace_symbols (array, size);

printf ("Obtained %zd stack frames./n", size);

for (i = 0; i < size; i++)
                printf ("%s/n", strings[i]);

free (strings);

exit(0);
}

int
main (void)
{
        signal(SIGSEGV, &dump);
        dummy_function ();

return 0;
}

编译运行结果如下:

xiaosuo@gentux test $ gcc -g -rdynamic g.c
xiaosuo@gentux test $ ./a.out
Obtained 5 stack frames.
./a.out(dump+0x19) [0x80486c2]
[0xffffe420]
./a.out(main+0x35) [0x804876f]
/lib/libc.so.6(__libc_start_main+0xe6) [0xb7e02866]
./a.out [0x8048601]

这次你可能有些失望,似乎没能给出足够的信息来标示错误,不急,先看看能分析出来什么吧,用objdump反汇编程序,找到地址0x804876f对应的代码位置:

xiaosuo@gentux test $ objdump -d a.out
 8048765:       e8 02 fe ff ff          call   804856c <signal@plt>
 804876a:       e8 25 ff ff ff          call   8048694 <dummy_function>
 804876f :       b8 00 00 00 00          mov    $0x0,%eax
 8048774:       c9                      leave

我们还是找到了在哪个函数(dummy_function)中出错的,信息已然不是很完整,不过有总比没有好的啊!
后记: 
本文给出了分析"段错误"的几种方法,不要认为这是与孔乙己先生的"回"字四种写法一样的哦,因为每种方法都有其自身的适用范围和适用环境,请酌情使用,或遵医嘱。

本文转自http://blog.chinaunix.net/space.php?uid=317451&do=blog&cuid=173718

段错误bug的调试的更多相关文章

  1. Linux下调试段错误 (gdb,core,ulimit)

    Linux环境下经常遇到某个进程挂掉而找不到原因,我们可以通过生成core file文件加上gdb来定位. (1)首先 在makefile中要增加编译调试选项 -g,才可以利用下面的gdb来调试 gc ...

  2. C&C++——段错误(Segmentation fault)

    C/C++中的段错误(Segmentation fault) Segment fault 之所以能够流行于世,是与Glibc库中基本所有的函数都默认型参指针为非空有着密切关系的.来自:http://o ...

  3. C/C++中的段错误(Segmentation fault)[转]

    Segment fault 之所以能够流行于世,是与Glibc库中基本所有的函数都默认型参指针为非空有着密切关系的. 来自:http://oss.lzu.edu.cn/blog/article.php ...

  4. linux64位系统中g++4.4.7下使用wcsncpy函数有造成段错误的BUG(其它g++版本号未知)

    一.描写叙述 眼下已经linux64位系统中g++4.4.7下发现了该bug.其它的版本号还未測试. 经測试,假设传入wcsncpy函数第一个參数(即目标缓冲区)的地址不能被4整除的话就必然会发生段错 ...

  5. 用gdb调试程序笔记: 以段错误(Segmental fault)为例

    用gdb调试程序笔记: 以段错误(Segmental fault)为例[转] 1.背景介绍2.程序中常见的bug分类3.程序调试器(如gdb)有什么用4.段错误(Segmental fault)介绍5 ...

  6. 你的java/c/c++程序崩溃了?揭秘段错误(Segmentation fault)(3)

    前言 接上两篇: 你的C/C++程序为什么无法运行?揭秘Segmentation fault (1) 你的C/C++程序为什么无法运行?揭秘Segmentation fault (2) 写到这里,越跟 ...

  7. Linux 下段错误 core文件

    什么是core dump? core的意思是内存,dump的意思是扔出来,堆出来:当一个程序奔溃时,在进程当前工作目录的core文件中复制了该进程的存储图像.core文件仅仅是一个内存映像(同时加上调 ...

  8. Linux环境下段错误的产生原因及调试方法小结(转)

    最近在Linux环境下做C语言项目,由于是在一个原有项目基础之上进行二次开发,而且 项目工程庞大复杂,出现了不少问题,其中遇到最多.花费时间最长的问题就是著名的“段错误”(Segmentation F ...

  9. linux Ubuntu(Segmentation fault)段错误出现原因及调试方法

      在linux下编译了一个程序,尝试运行的时候出现: Segmentation fault (core dumped) 初步确认为...完全不知道是什么玩意. 于是找度娘了. ----------- ...

随机推荐

  1. Linux下创建、查看、提取和修改静态库(*.a)

    先说明一点,静态库文件是由多个目标文件打包而成的,在windows下静态库文件的后缀是.lib,而在linux下静态库文件的后缀是.a(a是archive的缩写,也就是文档文件). 废话少说,下面直接 ...

  2. Swing UI - 可收起与开展内容面板实现演示

    基于JAVA Swing实现的自定义组件可折叠的JPanel组件 基本思想: 可折叠面板,分为两个部分-头部面板与内容面板 头部面板– 显示标题,以及对应的icon图标,监听鼠标事件决定内容面板隐藏或 ...

  3. Apache Hadoop最佳实践和反模式

    摘要:本文介绍了在Apache Hadoop上运行应用程序的最佳实践,实际上,我们引入了网格模式(Grid Pattern)的概念,它和设计模式类似,它代表运行在网格(Grid)上的应用程序的可复用解 ...

  4. css流式和弹性布局(未完)

    (子容器%父容器)*100 png透明ie6中filter:progid:DXImageTransfornm.Microsoft.AlphaImageLoader( src='路径',sizingMe ...

  5. Python模拟登录实战(一)

    今天,学习了模拟登录新浪微博.模拟登录主要有两种方式,一.利用Cookie:二.模仿浏览器的请求,发送表单. 法一: Cookie:指某些网站为了辨别用户身份而储存在用户本地终端上的数据(通常经过加密 ...

  6. mongodb授权登录

    mongodb版本为3.2(目前最新),演示的是linux下的mongodb授权认证 第一次登录不启动授权(mongo默认不启动) ./mongod --dbpath=/home/db/data -- ...

  7. java.lang.OutOfMemoryError: Java heap space错误及处理办法(收集整理、转)

    下面是从网上找到的关于堆空间溢出的错误解决的方法: java.lang.OutOfMemoryError: Java heap space ============================== ...

  8. c++中基本的语法问题

    的输出是? 答案:构造函数的初始化列表 字符串转化为整形的代码: enum Status{ kValid = 0,kInvalid }; int g_nStatus = kValid; int Str ...

  9. [Angular 2] Refactoring mutations to enforce immutable data in Angular 2

    When a Todo property updates, you still must create a new Array of Todos and assign a new reference. ...

  10. Android 中文 API (40) —— RatingBar

    Android 中文 API (40) —— RatingBar 前言 本章内容是 android.widget.RatingBar,译为"评分条",版本为Android 2.2 ...