Thursday, September 10, 2009

How to Debug Using gdb

Debugger:

After executing the binary executable we some times get unexpected results. The errors may be of dangling pointers, Stack over flow, Divide by zero etc, Which are very difficult to debug by looking at the Source code. GDB is a tool to debug the program it supports various languages like c,c++ etc.

gdb can take core dump file or executable file. Here executable is executed in the context of gdb. To debug using gdb at compilation time we have to give -g option.

gcc -g source.c -o source

Note: Electrical fence is used to check boundary errors. like size of array is 30 and we are storing value at 40 th location.
gcc source.c -lefence

After allocating memory using malloc, Always allign the memory using memalign. To avoid type casting.

Running a executable in gdb: gdb a.out
The you will get a gdb prompt.
The following commands has to be typed at gdb prompt.

run or r is used to run the program.
step is used to step by step execution, it also oes inside the function.
next is used to avoid function debug.


passing parameters: set args fastrevision blogspot
showing the arguments: show args
debug a already running program: attach process-id.
To get information about threads: info threads

Checkpoint: Setting a book mark to return that place easily.
checkpoint [lineno][function name]
during creation of checkpoint it saves all register, Stack values , Variables etc.

After executing some code.

To return back to check point: restart checkpoint-ID.
To know information about checkpoints: info checkpoints.
To delete checkpoint: delete checkpoint checkpoint-ID.

Listing of Program

To know your program where it is currently Running.
gdb> list

Note: To know the return value of previously executed program.
echo $?
Successful execution returns 0. Abnormal termination of program returns more than 0.

Breakpoint

To break the progrm after executing for some time. break command is used. For eg:
break lineno, function Name, Address.
while giving line numbers it always takes the first default file. To specify the file.
break file.c:

To add some condition: break 14 if ptr==0
To break the program only once: tbreak lineno
To get information about breakpoints: info breakpoints.
To ignore break point for some time: ignore breakpoint_no count.
To clear the breakpoint: clear [location][function name].
To disable break points: disable [breakpoints] [1..10]
To enable break points: enaable [breakpoints] [1..10]
We can execute some commands when it reaches a break point. By giving commands and end.
Commands is used to give commands which are in between commands and end to shell prompt.

Watch Points

To know what are the values. expression may be location,variable etc.
watch expression
rwatch expression
awatch expression
info watchpoints

To get information

ptype a: display what is the type of a.
info main
info source.

No comments:

Post a Comment