Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find segmentation fault from multiple files using GDB

I have been asked in an interview how can you debug segmentation fault in C program using GDB.

I told them we can compile our program with -g option so as it add debugging information to binary file and can read core dump file but then interviewer told me if he we have 3 to 4 files compiled together but one of them causing segmentation fault then how do we debug in GDB?

like image 948
Amit Singh Tomar Avatar asked Jan 23 '12 09:01

Amit Singh Tomar


1 Answers

$ gcc -ggdb s1.c s2.c s3.c -o myprog
$ gdb myprog
(gdb) run --arg1 --arg2

GDB will run the program as normal, when the segmentation fault occurs GDB will drop back to its prompt and it will be almost the same as running GDB with a core file. The major difference is there are some things you cannot do/print with a core file that you can when the program has crashed inside of GDB. (You can use print to call some functions inside the program, for example.)

You can also attach to an already running program using gdb --pid <the programs pid>.

Either with a core file or with one of the methods above, when you have the GDB prompt after the crash, type backtrace (or bt for short) and GDB will show you the stack at the time of the crash, including the file names and line numbers of each call and the currently executing line.

like image 137
SoapBox Avatar answered Sep 20 '22 13:09

SoapBox