Skip to main content
Basic Programming In C
Basic Programming In C

GDB Usage Example

The objective of this appendix is to illustrate on a very simple case how to use gdb (or lldb) to debug a program.

Using gdb

  1. Once the program is written, it must be compiled with the -g option (to include debug information).
  2. Launch the debugger with our program as an argument (by default a.out).
  3. Start program execution via run (or r).
  4. Identify bugs or errors
  5. Quit the program via quit (or q)

How to Identify Errors

In general, the program executes until it reaches:

  • its termination
  • an error
  • a breakpoint
  • an interrupt (CTRL+C)

Breakpoints

  • Set: break line_number or break function_name (b) (multiple breakpoints can be defined)
  • Delete: delete breakpoint_number
  • List breakpoints: info break
  • Delete all breakpoints: delete (d)
  • Disable: disable x or disable x-y
  • Enable: enable x or enable x-y, optionally add once for a single activation
  • Stop on condition: break x if condition
  • Watch: watch variable or watch expr
  • Resume:
    • continue (c) resumes until the next breakpoint/error/termination
    • next (n) executes the next instruction/function and pauses
    • step (s) executes the next instruction and pauses
    • finish: goes directly to the end of the current function
    • It is possible to use step x or next x to advance x lines at once.
    • It is possible to use continue x to skip the current breakpoint x times (useful for loops).
    • Pressing Enter repeats the last command

Displaying Variables

  • To display a local/global variable: print expr (p expr)
  • classic operators work ([], &, *)
  • It is possible to format the display: p/x p/d p/u p/o p/c p/f p/a to get results in decimal, octal, hexadecimal…

Call Stack

  • Inspect the stack bt or bt full
  • Navigate the stack up / down

Going Further

You can consult the following link https://www.rocq.inria.fr/secret/Anne.Canteaut/COURS_C/gdb.html which contains additional commands.

Practical Application

This is a program that contains several errors (uninitialized variable, passing a value instead of a pointer). We will illustrate how to use gdb to find these errors.

Example Program

exemple_gdb_init.c
#include <stdio.h>

int somme (int n)
{
    int result = 0;
    for (unsigned int i = 0; i < n; i++)
    {
        result += i;
    }
    return result;
}

void get_from_user (int n)
{
    do
    {
        printf ("Entrer un entier (>= 0)\n");
        scanf ("%d", &n);
    } while (n < 0);
}

int main ()
{
    int value;
    get_from_user (value);
    printf ("Somme = %d\n", somme (value));
    return 0;
}

Using gdb