Gdb: Difference between revisions

From miki
Jump to navigation Jump to search
(Created page with '== References == * [http://www.unknownroad.com/rtfm/gdbtut/gdbsegfault.html 7.2 Example Debugging Session: Segmentation Fault Example] * == Compile with debug symbols == * Opti…')
 
Line 7: Line 7:
<source lang="bash">
<source lang="bash">
gcc -g program.c # -g : debug symbols
gcc -g program.c # -g : debug symbols
</source>

== GDB invocation ==
<source lang="bash">
gdb a.out
gdb a.out core.1234
</source>
</source>


Line 35: Line 41:
;next
;next
:Step to next instruction
:Step to next instruction

== GDB examples ==
=== Simple Segmentation Fault Example ===
(From [http://www.unknownroad.com/rtfm/gdbtut/gdbsegfault.html])
{| class="wikitable" width=100%
|-
|width=50%|Example program <tt>segfault.c</tt>:

<source lang="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;
}
</source>
|Compile and launch gdb:
<source lang="bash">
gcc -g segfault.c
gdb a.out
</source>
The debug session
<source lang="gdb">
run
backtrace
frame 3
print buf
kill
break segfault.c:8
run
print buf
next
print buf
</source>

Revision as of 11:03, 22 July 2011

References

Compile with debug symbols

  • Option -g:
gcc -g program.c           # -g : debug symbols

GDB invocation

gdb a.out
gdb a.out core.1234

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
print VAR
Print value of variable VAR
kill
Kill current program
break FILELINE
Insert a breakpoint at file FILE, line LINE
next
Step to next instruction

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