咱们在用C/C++语言写程序的时侯,内存管理的绝大部分工做都是须要咱们来作的。实际上,内存管理是一个比较繁琐的工做,不管你多高明,经验多丰富,难 免会在此处犯些小错误,而一般这些错误又是那么的浅显而易于消除。可是手工“除虫”(debug),每每是效率低下且让人厌烦的,本文将就"段错误"这个 内存访问越界的错误谈谈如何快速定位这些"段错误"的语句。
下面将就如下的一个存在段错误的程序介绍几种调试方法:linux
dummy_function (void) { unsigned char *ptr = 0x00; *ptr = 0x00; } int main (void) { dummy_function (); return 0; }
做为一个熟练的C/C++程序员,以上代码的bug应该是很清楚的,由于它尝试操做地址为0的内存区域,而这个内存区域一般是不可访问的禁区,固然就会出错了。咱们尝试编译运行它:程序员
xiaosuo@gentux test $ ./a.out 段错误
果真不出所料,它出错并退出了。
1.利用gdb逐步查找段错误:
这种方法也是被大众所熟知并普遍采用的方法,首先咱们须要一个带有调试信息的可执行程序,因此咱们加上“-g -rdynamic"的参数进行编译,而后用gdb调试运行这个新编译的程序,具体步骤以下:debug
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大小,再试:code
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;