Getting through loops

This loop goes round more than a hundred times. Typing next and print n each time would take all day.

display, until and advance

Level 10 of 13 · interactive GDB exercise · runs in your browser

Start this exercise

What you will learn

Keep an eye on values while stepping through a loop, and run to a later line without setting a breakpoint.

display n shows n after every stop. Pressing Enter on an empty line repeats your last command.

When you have seen enough, until 13 runs until line 13 is next. No breakpoint needed.

The exercise

Watch n for a few trips round the loop, then jump straight to the return.

You work in a real GDB session on the program below. A breakpoint on collatz_steps was set and the program was started; it is paused at the first line of collatz_steps.

#include <stdio.h>

int collatz_steps(int n) {
    int steps = 0;
    while (n != 1) {
        if (n % 2 == 0) {
            n = n / 2;
        } else {
            n = 3 * n + 1;
        }
        steps++;
    }
    return steps;
}

int main(void) {
    int steps = collatz_steps(27);
    printf("27 takes %d steps\n", steps);
    return 0;
}

main.c, compiled with gcc -g -O0 -std=c11 -Wall -fno-omit-frame-pointer -fno-stack-protector -no-pie -fno-pie for 32-bit x86 Linux.

GDB commands you will use

display <expr>
Show an expression automatically after every stop (display n, display/x n).
undisplay [n]
Stop showing display number n, or all of them. info display lists them.
(Enter)
An empty line repeats the last command. Handy after next, step or stepi.
until [where]
Like next, but never jumps back up in a loop. With a line: run until that line (until 13).
advance <where>
Run until a line or function is reached, without setting a breakpoint (advance 13).
tbreak <where>
One-shot breakpoint: it deletes itself the first time it is hit.
next
Run the current line; step over function calls (n).
finish
Run until the current function returns; shows the return value.
print <expr>
Evaluate and show an expression (p total, p &x, p *a, p/x n).

Common mistakes

Try it in your browser