Professional Documents
Culture Documents
GDB tutorial
There is probably no person capable of writing complicated pieces of code
which will work from the first run. Once you get over the compilation
errors, you might still expect some runtime errors, which are worse. If the
compiler is good enough to give us hints about our errors (either we have
typos, or we use undefined structures, or the function call and function
header do not match), at runtime errors are more subtle and usually harder
to catch.
What kind of errors can we expect during runtime? Referencing a NULL
pointer, working with unopened files, division by 0 or simple error which are
correct for the compiler (for example an if (x = 2) is correct for the compiler,
but for sure we didnt want that to happen).
For simple programs we can use printf(message\n) to help us debug.
This will give us some hints about where our code crashes. Please be careful
when using this method of debugging. Every message must end with \n, or
else what we see might not be correct. The printf function only prints in one
of the following situation: the internal buffer it uses is full, and it will be
ejected to the output; or an explicit call is made to free the buffer (by using
\n for example).
Of course, this method is not the best. It is good for small codes, for codes
written by you and it is good if you also have hints about what might be
wrong.
What is there to do in all the other cases?
gdb a.out -> run / run arg1 arg2 / run < file
gdb args ./a.out arg1 arg2 -> run
quit
Useful commands
Exercises
Please download the archive attached to this laboratorys folder.
1. Exercise 1
Compile the ex1.c file using -g flag. Do not look at the source code yet.
Try to run the executable like this ./a.out. Does it break? GOOD.
Now open the executable with GDB and try to find the source of your
failure. After you talk with your assistant, try to repair this failure. Please
make sure no one ever can make this mistake again.
2. Exercise 2
Now your ex1.c file compiles and also runs OK. But are you sure it is ok?
Are you always unlucky? Or did you find any strange behavior? Use gdb to
investigate which might be the problem.
3. Exercise 3
Am ramas in pana de idei ))