Monday, February 14, 2011

gdb: script

Recently I discovered the easy way of debugging in gdb - GDB scripting. Often while debugging I got stuck wondering what the value of an item in a complex data structure was. Till a few days ago, I used to modify the code to add debug messages and then recompile and then rerun. This wasted a lot of time.
Then one day after having wasted a lot of time, in recompile and rerun, I decided to use GDB scripts (which I had known since long, but had never used). And it is really fun now. I save a lot of time in debugging.
A sample script that I used to count the number of elements in a linked list (which we use a lot in our code) is below:

define cntList
set $l = $arg0
set $i = 0
if ($l == 0)
printf "NULL list found\n"
else
set $n = $l
while ($n != 0)
set $i = $i+1
set $n = $n->next
end
end
printf "list size %d\n", $i
end
document cntList
count the number of elements in the list
Usage: cntList ptr
end

No comments: