Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  1. Debug line by line
  2. Put printfs in the code to narrow down.

Edits:

  1. bt / where on gdb give No stack.
  2. Helpful suggestion
like image 663
Rohit Avatar asked Feb 02 '09 23:02

Rohit


People also ask

How do you find line segment fault number?

GDB can give you the line where a crash occurred with the "bt" (short for "backtrace") command after the program has seg faulted. This will give you not only the line of the crash, but the whole stack of the program (so you can see what called the function where the crash happened).

What is segmentation fault signal?

On a Unix operating system such as Linux, a "segmentation violation" (also known as "signal 11", "SIGSEGV", "segmentation fault" or, abbreviated, "sig11" or "segfault") is a signal sent by the kernel to a process when the system has detected that the process was attempting to access a memory address that does not ...

What does segmentation fault 11 mean?

When Segmentation fault 11 occurs, it means that a program has attempted to access a memory location that it's not allowed to access. The error can also occur if the application tries to access memory in a method that isn't allowed.


2 Answers

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.

like image 70
rck Avatar answered Sep 17 '22 15:09

rck


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 :-)

like image 22
Jonas Kölker Avatar answered Sep 20 '22 15:09

Jonas Kölker