COMP2521
Data Structures & Algorithms
Week 4.1
GDB
1
In this lecture
Why?
Debugging with print statements is not a scalable solution
to debugging very complex or longprograms
What?
GDB
Valgrind
2
Basis of lecture
While this lab isn’t marked, we do expect students to complete it. If
you seek help during labs or help sessions, your tutor will expect you
to be able to show them your attempts to debug it with GDB and
valgrind.
This lecture is simply a walkthrough and elaboration of a lab11 which
focuses on GDB and valgrind.
3
https://cgi.cse.unsw.edu.au/~cs2521/21T2/lab/11/questions
GDB
GDB is a portable debugger that we can use to debug (during
runtime) our C programs.
To run our code with GDB, we must compile our with the GCC flag -g.
This adds extra information to the executable so that it can be
“watched” by GDB when running. Think of it like littering your code
with print statements (except much smarter).
gcc -Wall -Werror -g -o program program.c1
4 . 1
GDB Key Commands
$ gcc -Wall -Werror -g -o program program.c
$ gdb ./program
1
2
Command Description Example Shorthand
example
run Starts your program and runs until the next breakpoint / end of
program / crash
run r
continue Continues your program from a breakpoint until the next
breakpoint / end of program / crash
continue c
break [filename].c:[line#] Sets a breakpoint for run/continue to stop at break set.c:122 b set.c:122
break [function_name] Sets a breakpoint for run/continue to stop at break SetCreate b SetCreate
next Execute another line of code, but don’t go any deeper (don’t
enter a function)
next n
step Execute another line of code, including going deeper into a
function
step s
print [variable_name] Prints variables at a moment in time (at the breakpoint) print q->item p q->item
4 . 2
GDB Example Flow
gdb ./program
break file.c:123
break functionName run
print var1
next
print var1
continue[segmentation fault]
4 . 3
Valgrind
Valgrind is a similar tool to GDB, except it runs your program to
detect any memory leaks or un-free’d memory.
$ gcc -Wall -Werror -g -o program program.c
$ valgrind ./program
1
2
5