Pointers are addresses

A pointer is a variable that holds an address. *a means: the thing at that address.

A pointer holds the address of another object

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

Start this exercise

What you will learn

Connect a pointer's value to the address of the object it refers to, and watch a write through a pointer change a variable in another frame.

Here a and b point at x and y over in main. Follow the arrows on the right.

The exercise

Step through swap and watch x and y in main change.

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

#include <stdio.h>

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main(void) {
    int x = 10;
    int y = 20;
    swap(&x, &y);
    printf("x = %d, y = %d\n", x, y);
    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

print <expr>
Evaluate and show an expression (p total, p &x, p *a, p/x n).
next
Run the current line; step over function calls (n).
frame <n>, up, down
Select a frame to inspect. Does not move execution.
x/<n><fmt><size> <addr>
Examine raw memory, e.g. x/4xw &values (4 hex words), x/8xb &p (8 hex bytes).
info args
Show the selected frame's arguments.
ptype <expr>
Show the type of an expression or the layout of a struct.

Common mistakes

Try it in your browser