Saturday, April 23, 2016

GDB Tutorial to find Code causing Segmentation Fault in C/C++ programs


Basically, you have to compile your program like this :

gcc -g test.c -o test

where in, "test" is the output file name. And -g is used to put debugging information too in the "test" file. Read the above Tutorials Point link to know more about it.
So, you execute the program like this :

./test

Later, if you get segmentation fault, just do this :

gdb test

Then a prompt comes up, type

r

This will run the program, and it will run with debugging mode on I guess. So, when there is a segmentation fault, it will show you the line number and the line of code itself. For example, see the below screen shots :
I am writing a code to basically dereference a null pointer.



When I type "r" command [ Look for "(gdb)" - the prompt, in the screenshot ] , the program runs, and you see the "starting program : ..." message and you see the segmentation fault and where it was received.


And then I type "q" command to quit and say "y" to confirm it. Check the Tutorials Point link to find out more GDB commands. But these two commands should be enough to find out the code causing segmentation fault.



A friend asked if gdb is installed in our lab computers. Well, I think it's a very general package like gcc, and when I tried "sudo apt-get install gdb" and the same for gcc, the prompt said it is installed automatically under some package named "linux-image-extra-xyz.abc.
pqr-generic" something, as if they are all in a single basic general package. So, I think it should be installed. So, just remember these commands and try it out in your programs in case you have segmentation faults in them.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.