Gdb: Difference between revisions

From miki
Jump to navigation Jump to search
Line 38: Line 38:
;frame [FRAME]
;frame [FRAME]
:Select and print stack frame
:Select and print stack frame

;info locals
;info args
:Print information on local variables / function arguments in the <u>current</u> frame


;print VAR
;print VAR

Revision as of 11:34, 22 July 2011

References

Prepare debug session

  • Compile with debug symbols, use option -g:
gcc -g program.c               # -g : debug symbols
gcc -g -O0 program.c           #  ... -O0: disable optimization
  • Force core dumps (see bash help ulimit):
ulimit -c unlimited
./a.out
# Segmentation fault (core dumped)

GDB invocation

gdb a.out
gdb a.out core.1234           # If coredump available

GDB commands

help
Get help on commands
run [ARGS]
Start debugged program. Arguments may include wildcards (*) and redirections (<, <<...)
backtrace [COUNT]
bt [COUNT]
where [COUNT]
Print backtrace of all stack frames, or innermost (outermost) COUNT frames if COUNT>0 (COUNT<0)
frame [FRAME]
Select and print stack frame
info locals
info args
Print information on local variables / function arguments in the current frame
print VAR
Print value of variable VAR
kill
Kill current program
b FILE:LINE
break FILE:LINE
Insert a breakpoint at file FILE, line LINE
next
Step to next instruction
b main Put a breakpoint at the beginning of the program
b Put a breakpoint at the current line
b N Put a breakpoint at line N
b +N Put a breakpoint N lines down from the current line
b fn Put a breakpoint at the beginning of function "fn"
d N delete breakpoint number N
info break list breakpoints
r Run the program until a breakpoint or error
c continue running the program until the next breakpoint or error
f Run until the current function is finished
s run the next line of the program
s N run the next N lines of the program
n like s, but don't step into functions
u N run until you get N lines in front of the current line
p var print the current value of the variable "var"
bt print a stack trace
u go up a level in the stack
d go down a level in the stack
q Quit gdb

GDB examples

Simple Segmentation Fault Example

(From [1])

Example program segfault.c:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
  char *buf;

  buf = malloc(1<<31);

  fgets(buf, 1024, stdin);
  printf("%s\n", buf);

  return 1;
}
Compile and launch gdb:
gcc -g segfault.c
gdb a.out

The debug session

run
backtrace
frame 3
print buf
kill
break segfault.c:8
run
print buf
next
print buf