Generally, when you write and run a program, and then receive a Segmentation fault, you’d be confused where the problem happens. You use gdb to debug the executable file, but it usually gives you an error notice in some dynamic library. What you want to know may be the line number in your program, though.
That’s because you don’t try core dump. With core dump, the system will write memory state to a core file when a program exits abnormally. Combined with the symbol table generated by -g (or -ggdb), you can locate the line where the problem happens.
ulimit -S -c
to check whether core file size is limited. If it’s 0, run
ulimit -S -c unlimited
and check again. If it’s still 0, change -S to -H and run again.
Second, compile your program with -g or -ggdb option
gcc -ggdb -o a a.c
Finally, run your program. If it has a segmentation fault, you’ll get the notice:
Segmentation fault (core dumped)
There should be a new file named core or core.[pid]. Now you can use
gdb a core
to debug the program. gdb should stop at the line of error. Use bt to see where it comes from.
Finally, some useful materials: