Into and out of functions

next steps over a function call. step goes into it. finish runs until the current function returns.

step, next and finish

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

Start this exercise

What you will learn

Choose between stepping over a call, stepping into it, and running until the current function returns.

Every call in progress gets a frame. Watch the call stack on the right grow and shrink.

The exercise

Step into square, finish out of it, then reach the return in sum_of_squares.

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

#include <stdio.h>

int square(int n) {
    int result = n * n;
    return result;
}

int sum_of_squares(int a, int b) {
    int first = square(a);
    int second = square(b);
    return first + second;
}

int main(void) {
    int answer = sum_of_squares(3, 4);
    printf("answer = %d\n", answer);
    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

step
Run the current line; step into function calls (s).
next
Run the current line; step over function calls (n).
finish
Run until the current function returns; shows the return value.
backtrace
List the active function calls, innermost first (bt).
print <expr>
Evaluate and show an expression (p total, p &x, p *a, p/x n).
info locals
Show the selected frame's local variables.

Common mistakes

Try it in your browser