Line number of segmentation fault

Is there any gcc option I can set that will give me the line number of the segmentation fault?

I know I can:

  • Debug line by line
  • Put printfs in the code to narrow down.
  • Edits:

  • bt / where on gdb give No stack.
  • Helpful suggestion

  • I don't know of a gcc option, but you should be able to run the application with gdb and then when it crashes, type where to take a look at the stack when it exited, which should get you close.

    $ gdb blah
    (gdb) run
    (gdb) where
    

    Edit for completeness:

    You should also make sure to build the application with debug flags on using the -g gcc option to include line numbers in the executable.

    Another option is to use the bt (backtrace) command.


    Here's a complete shell/gdb session

    $ gcc -ggdb myproj.c
    $ gdb a.out
    gdb> run --some-option=foo --other-option=bar
    (gdb will say your program hit a segfault)
    gdb> bt
    (gdb prints a stack trace)
    gdb> q
    [are you sure, your program is still running]? y
    $ emacs myproj.c # heh, I know what the error is now...
    

    Happy hacking :-)


    You can get gcc to print you a stacktrace when your program gets a SEGV signal, similar to how Java and other friendlier languages handle null pointer exceptions. See my answer here for more details:

  • how to generate a stacktace when my C++ app crashes ( using gcc compiler )
  • The nice thing about this is you can just leave it in your code; you don't need to run things through gdb to get the nice debug output.

    If you compile with -g and follow the instructions there, you can use a command-line tool like addr2line to get file/line information from the output.

    链接地址: http://www.djcxy.com/p/86046.html

    上一篇: 你如何阅读segfault内核日志消息

    下一篇: 分段故障的行号