快速定位段错误

时间:2023-02-20 21:36:21

1.先写一个会产生段错误的程序:

test.cpp

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

void fun()
{
char *ptr;
memcpy(ptr,
"abc", 3);
}

int main()
{
fun();

return 0;
}

2.编译程序 g++ -g test.cpp -o test

3.使用ulimit -c unlimited命令,使程序产生段错误时可以产生core文件

4.gdb test core.*** 调试程序

[root@localhost mnt]# gdb test core.2660 
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 <http://gnu.org/licenses/gpl.html>
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 "i686-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /mnt/test...done.
[New LWP 2660]
Core was generated by `./test'.
Program terminated with signal 11, Segmentation fault.
#0 0xb75f7e5a in __memcpy_ssse3_rep () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.17-105.el7.i686 libgcc-4.8.5-4.el7.i686 libstdc++-4.8.5-4.el7.i686
(gdb) where
#0 0xb75f7e5a in __memcpy_ssse3_rep () from /lib/libc.so.6
#1 0x080484e1 in fun () at test.cpp:7
#2 0x080484ee in main () at test.cpp:12
(gdb) q

 从上图可以看到,程序在main()->fun()->memcpy()处产生段错误。