Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Linux + C – Debugging with GDB

Alright, enough theory. Time to actually debug something!

Debugging: input.c

It seems only fitting that we debug the one program which I deliberately wrote with major (critical?) bugs.

To start, we navigate to our Program directory and run the command:

gdb input

First, let’s run the program as we intended it. We simply tell gdb to “run”, and it acts normally.

run

2015-09-14-212249_1920x1080_scrot

Now we’ll run it normally, but in a way that we know it should not work. Specifically, we’ll feed a character string to the age input, and a super-long string to the last-name input.

2015-09-14-212421_1920x1080_scrot

So we know that didn’t work properly. Now let’s set a breakpoint at line 27.

break input.c:27

2015-09-14-212732_1920x1080_scrot

Now we’ll run it again, but check on some of the inputs using print.

run

print age

2015-09-14-212732_1920x1080_scrot

When we’re stopped at line 27, we can see that our code set the age to 0, because it didn’t know what else to do. Right quick, let’s change that to 28 using set.2015-09-14-213344_1920x1080_scrot

set variable age=28

2015-09-14-213703_1920x1080_scrot

Note: The debugger has a default variable named age. We have to use “set variable” instead of plain “set” to differentiate between the two.

It looks fine, so let’s skip on down with next.

next

next

“Bob was here” <ENTER>

next

<ENTER>

<ENTER>

2015-09-14-213703_1920x1080_scrot

Boring. Let’s just let it continue normally until the loop is over using until.

until input.c:39

2015-09-14-213703_1920x1080_scrot

Yes, it’s the same screenshot three times in a row. It can be remarkably difficult to remember to hit the Print Screen button.

Boom! No more loop. Now let’s skip down a ways to the first name input.

n

<ENTER>

2015-09-14-213800_1920x1080_scrot

Now we have filled all of our variables. Let’s look at last and last_copy before we compare them.

print last

print &last

print last_copy

print &last_copy

2015-09-14-213909_1920x1080_scrot

We know it will work right now, because last and last_copy agree. However, just for giggles, we should change last_copy using set.

set last_copy = “Hi Folks”

print last_copy

2015-09-14-214051_1920x1080_scrot

continue

2015-09-14-214114_1920x1080_scrot

Now, look at that. We managed to make our code do a quick replacement. Now, we can see the error-tree execute properly.

Conclusion

That’s about all you need to know to get very familiar with gdb. Just use these techniques and Google everything you can’t quite figure out.

photo by: