Skip to content
systemcoding.dev
Debugging

Print Variables, Arrays and Structs in GDB

Use GDB's print, display, ptype and info locals to read scalars, arrays, structs and pointers, and change output with format letters, @ slices and set print.

6 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the GNU, C and LLVM logos.

Stopping a program is only useful if you can then see what it holds. GDB's print command evaluates a C expression in the context of the stopped frame and shows the result using the type from the debug information. That means you can print a plain int, a whole array, a struct with its fields named, a pointer and the thing it points at, or the result of arithmetic on any of them. This post works through each case on one program, and then covers the controls that make large values readable: format letters, the @ operator for slices, display for values you want after every step, and the set print options. Output comes from GDB 16.3 with GCC 14, built with -g -O0 on x86-64 Linux.

The program

A small inventory of items, each a struct, gives us a scalar, an array, a nested struct and a pointer to inspect.

items.cc
#include <stdio.h>
#include <string.h>

struct dims {
    int width;
    int height;
};

struct item {
    int id;
    char name[16];
    double price;
    struct dims box;
};

static double total_price(const struct item *items, int count)
{
    double sum = 0.0;
    for (int i = 0; i < count; i++)
        sum += items[i].price;
    return sum;
}

int main(void)
{
    struct item stock[3] = {
        {1, "bolt", 0.25, {2, 1}},
        {2, "washer", 0.10, {3, 3}},
        {3, "bracket", 2.50, {10, 4}},
    };
    int counts[4] = {10, 20, 30, 40};
    struct item *cursor = &stock[1];
    double total = total_price(stock, 3);
    printf("%.2f %d %s\n", total, counts[0], cursor->name);
    return 0;
}

The total is 0.25 + 0.10 + 2.50 = 2.85, so the program prints 2.85 10 washer. Build it, stop on the line with total_price, and look around.

Shell
gcc -g -O0 -Wall -Wextra -o items items.c
gdb -q ./items
Text
(gdb) break 33
Breakpoint 1 at 0x1257: file items.c, line 33.
(gdb) run
Starting program: /home/dev/items

Breakpoint 1, main () at items.c:33
33	    double total = total_price(stock, 3);

Scalars and expressions

print takes any expression. A variable name shows its value, and the output is stored in the value history as $1, $2 and so on.

Text
(gdb) print counts[0]
$1 = 10
(gdb) print counts[1] + counts[2]
$2 = 50
(gdb) print $1 * 3
$3 = 30
(gdb) print sizeof(struct item)
$4 = 40
(gdb) print/x counts[3]
$5 = 0x28

$1 * 3 shows that history values are ordinary operands. $ alone is the last value and $$ the one before it. The size of struct item is 40 bytes here because the 4-byte id, 16-byte name and 4 bytes of padding come before the 8-byte double, followed by an 8-byte struct dims; GCC on x86-64 aligns the double to 8. The last line used a format letter, which is covered below.

Arrays and the @ operator

Printing an array name prints every element. That is what you want for counts and not for a thousand-element buffer.

Text
(gdb) print counts
$6 = {10, 20, 30, 40}
(gdb) print counts[1]@2
$7 = {20, 30}

The binary @ operator makes an artificial array: the left side is the first element, the right side is the count. It is how you look at a slice of an array, or at memory behind a pointer. If a function receives int *p, GDB sees one int and no length, so print *p@8 is the way to show eight elements starting there. Give @ a variable count, such as *values@count, and it follows the program's own bookkeeping. The left operand has to be in memory, so a register-only value cannot be the base.

Long arrays are cut. GDB's print elements limit defaults to 200, and it ends the output with ... when it truncates. Raise it with set print elements 1000, or set it to unlimited to see everything.

Structs and nested structs

A struct prints with field names and braces.

Text
(gdb) print stock[0]
$8 = {id = 1, name = "bolt", '\000' <repeats 11 times>, price = 0.25, box = {width = 2, height = 1}}
(gdb) print stock[0].box
$9 = {width = 2, height = 1}
(gdb) print stock[2].box.width * stock[2].box.height
$10 = 40

The name field shows how GDB prints a char array: the string, then the trailing zero bytes as a repeat count. "bolt", '\000' <repeats 11 times> means four letters plus eleven NULs, which with the terminating byte fills 16. The option set print null-stop on stops printing at the first NUL, which shortens it to name = "bolt".

Two options make wide structs readable. set print pretty on prints one field per line with indentation.

Text
(gdb) set print pretty on
(gdb) print stock[1]
$11 = {
  id = 2,
  name = "washer", '\000' <repeats 9 times>,
  price = 0.10000000000000001,
  box = {
    width = 3,
    height = 3
  }
}

The price shows as 0.10000000000000001, not 0.10. That is the nearest double to 0.1, printed with 17 significant digits, and it is correct; the program's %.2f rounds it. print/f does not change the precision, so if you want a shorter number, use arithmetic like print (int)(stock[1].price * 100), which prints 10.

Pointers

A pointer prints as an address, and you follow it with * or ->, as in C.

Text
(gdb) print cursor
$12 = (struct item *) 0x7fffffffe0f0
(gdb) print *cursor
$13 = {
  id = 2,
  name = "washer", '\000' <repeats 9 times>,
  price = 0.10000000000000001,
  box = {
    width = 3,
    height = 3
  }
}
(gdb) print cursor->name
$14 = "washer", '\000' <repeats 9 times>
(gdb) print cursor - stock
$15 = 1

cursor was assigned on line 32, so at this stop it holds the address of stock[1]. Subtracting two pointers into the same array gives an element index, exactly as C would. Stack addresses vary with your environment, so yours will differ.

A char * prints the pointer and the string it points to. If the pointer is bad, GDB prints <error: Cannot access memory at address 0x...> instead of crashing, which is a useful diagnostic in itself.

Format letters

print/FMT changes how a value is shown, without changing the value. The letters you will use most are x for hexadecimal, d for signed decimal, u for unsigned, o for octal, t for binary, c for character, f for float and a for an address with its nearest symbol.

Text
(gdb) print/x counts
$16 = {0xa, 0x14, 0x1e, 0x28}
(gdb) print/t counts[0]
$17 = 1010
(gdb) print/c stock[0].name[0]
$18 = 98 'b'
(gdb) print/x stock[0].id
$19 = 0x1

print/x applied to an array or a struct applies to every element. A format letter on a double with x converts the integer value in recent GDB, not the bit pattern. To see the bits of a double, reinterpret it: print/x *(long *)&stock[0].price. Reaching for x/2gx &stock[0].price with the memory examine command is the other route, and the next post in this series covers it.

Types and locals

ptype shows the full definition of a type or expression, and whatis shows only its name.

Text
(gdb) ptype struct item
type = struct item {
    int id;
    char name[16];
    double price;
    struct dims box;
}
(gdb) whatis stock
type = struct item [3]

info locals prints every local variable in the current frame, and info args the function arguments. On a stop in main, info locals lists stock, counts, cursor and total, with whatever each holds right now. Variables that have not been assigned yet show leftover stack contents, so a garbage value before its line has run is expected, not a bug.

Watching values change: display

If you want the same expression after every stop, use display. It prints the expression each time the program stops and numbers it.

Text
(gdb) display total
1: total = 6.9533558073973168e-310
(gdb) next
34	    printf("%.2f %d %s\n", total, counts[0], cursor->name);
1: total = 2.8500000000000001

The first value is stack garbage before line 33 ran, and varies by run. After next, total is 2.85 in its 17-digit form. info display lists them, undisplay 1 removes one, and display/x counts[0] takes a format letter.

Limits to know

print evaluates in the current frame, so a variable from the caller needs up first, or a frame-qualified name through a function scope such as print 'items.c'::stock. An optimised build may report <optimized out> for a variable that lives in no register at that point, and the cure is a lower optimisation level, not a different command. And print can call functions in the program, as in print total_price(stock, 3), which runs real code in the stopped process. Do that only when the function has no side effects you care about.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.