这种方法需要用到Linux提供的core dump机制:当程序中出现内存操作错误时,会发生崩溃并产生核心文件(core文件)。使用GDB可以对产生的核心文件进行分析,找出程序是在什么时候崩溃的和在崩溃之前程序都做了些什么。
首先,你的Segmentation Fault错误必须要能重现(废话…)。
(1)无论你是用Makefile来编译,还是直接在命令行手工输入命令来编译,都应该加上
-g
选项。
(2)一般来说,在默认情况下,在程序崩溃时,core文件是不生成的(很多Linux发行版在默认时禁止生成核心文件)。所以,你必须修改这个默认选项,在命令行实行:
(3)运行你的程序,不管用什么方法,使之重现Segmentation Fault错误。
(4)这时,你会发现在你程序同一目录下,生成了一个文件名为
core.***
的文件,即核心文件。例如,“core.15667”这样的文件。
(5)用GDB调试它。假设你的可实行程序名为test,则在命令行实行:
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 "i586-suse-linux"... Using host libthread_db library "/lib/libthread_db.so.1". warning: core file may not match specified executable file. warning: Can't read pathname for load map: Input/output error. Reading symbols from /usr/lib/libstdc++.so.6...done. Loaded symbols for /usr/lib/libstdc++.so.6 Reading symbols from /lib/libm.so.6...done. Loaded symbols for /lib/libm.so.6 Reading symbols from /lib/libgcc_s.so.1...done. Loaded symbols for /lib/libgcc_s.so.1 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 `/home/YHang/cscf/make32/../../pplat/tools/sip_diam_mml_suse'. Program terminated with signal 11, Segmentation fault. #0
0xb7e072dd in opendir () from /lib/libc.so.6 #0
0xb7e072dd in opendir () from /lib/libc.so.6 #1
0x08048d6f in getFilesName (dir=0x0) at sip_diam_mml.cpp:25 #2
0x0804900d in main () at sip_diam_mml.cpp:257 问题即可定位
|