I'm trying to find the segmentation fault in a c file that is used by an executable but I haven't found any leads. Does anyone know how to do this?
-
1Did you really find nothing on the whole web about debugging with gdb? – kaylum Dec 02 '16 at 04:53
-
@kaylum It's like fighter club - to find something about what you need, you should know what you need. and modern search engines are bad at new topic.. they try to push away anything new by relevancy. Good guide https://beej.us/guide/bggdb/ – Swift - Friday Pie Dec 02 '16 at 05:00
-
I couldn't find anything. From the link that Swift gave me I guess I was being to specific with my search query and not searching broad enough. – user3304124 Dec 02 '16 at 05:20
2 Answers
Here is a sample program that would definitely cause segmentation fault :
include
int main() {
int *pVal = NULL;
printf("ptr value is : %d", *pVal);
return 0;
}
You need to compile in debug mode in order to add additional debug information in executable file:
gcc -g segFault.c
Then all you need is to run gdb and give that the executable file path (i.e a.out in this case). Then by just running it you can see that gdb highlights the line causing segmentation fault.
~/Dropbox/cprog/demos : $ gdb a.out
GNU gdb (GDB) 7.12
Copyright (C) 2016 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 "x86_64-apple-darwin15.6.0".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...Reading symbols from /Users/rohankumar/Dropbox/cprog/demos/a.out.dSYM/Contents/Resources/DWARF/a.out...done.
done.
(gdb) run
Starting program: /Users/rohankumar/Dropbox/cprog/demos/a.out
Program received signal SIGSEGV, Segmentation fault.
0x0000000100000f62 in main () at segFault.c:6
6 printf("ptr value is : %d", *pVal);
You can also print the values and see stacktrace of program. You can read more about gdb here .
Happy coding!

- 5,427
- 8
- 25
- 40
Run gdb and run your program from gdb, then use backtrace. you 'll get stack frame, which you can walk through by fram command and use print to check variables' values. Check gdb tips\docs over internet. You can use gdb to load already existing core file, generated by crashed program, to find spot where problem occured. Loaded core file is equal to state at crash point, you just usebacktrace.
Answer on your question was here: Determine the line of C code that causes a segmentation fault?

- 1
- 1

- 12,777
- 2
- 19
- 42