I want to know how can I get to know which line is causing segmentation fault in c language in unix terminal
Asked
Active
Viewed 1,987 times
1
-
2Run your code in a debugger (e.g. GDB). – Oliver Charlesworth Dec 04 '17 at 20:12
-
Step through your code one line at a time until it crashes. – Sergey Kalinichenko Dec 04 '17 at 20:13
-
3Segmentation fault is a symptom of an *undefined behavior*. The line at which is is happening is not necessarily the line causing it. – Eugene Sh. Dec 04 '17 at 20:13
-
1Where your code crashes is not necessarily where the crash was caused. Run your code through [valgrind](http://valgrind.org) which will tell you exactly what you're doing wrong. – dbush Dec 04 '17 at 20:14
-
@oliverCharlesworth could you please specify me how to use gdb on mac terminal? – Piyush Mehta Dec 04 '17 at 20:14
-
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Jean-François Fabre Dec 04 '17 at 20:17
-
If you are not ready for a debugger you could use the "divide and conquer" approach by inserting printed cues. This is a sort of binary chop way to find where the failure happens. Make sure each message is flushed to the console. However: the better way is to build and test and stretch the program as you develop each tiny step, in the first place. So when it fails, you don't have the needle haystack problem but just a few places to look. – Weather Vane Dec 04 '17 at 20:21
-
Google "gdb tutorial" – Jabberwocky Dec 04 '17 at 20:42
1 Answers
1
- Rebuild with debugging symbols (add
-g
flag when compiling). - Run through
gdb
.gdb <binary name>
- (In
gdb
)run <binary name> <args>
- On crash, use
backtrace
command to see stack trace. The offending line will be at the top of the stack, but you may need to look further down in case the segfault is in some library code.

0x5453
- 12,753
- 1
- 32
- 61