Objects that outlive a call

malloc hands out memory that outlives the function that asked for it. It is not in any frame: you reach it only through pointers.

Dynamically allocated objects are reached only through pointers

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

Start this exercise

What you will learn

Distinguish a pointer stored in a stack frame from the allocated object it refers to, and follow a chain of pointers through a linked list.

list lives in main. The nodes live elsewhere, under Reached through pointers.

The exercise

Watch the list get built, then pause in the loop and follow the chain.

You work in a real GDB session on the program below. A breakpoint on push was set and the program was started; it is paused in the first call to push.

#include <stdio.h>
#include <stdlib.h>

struct node {
    int value;
    struct node *next;
};

struct node *push(struct node *head, int value) {
    struct node *n = malloc(sizeof *n);
    n->value = value;
    n->next = head;
    return n;
}

int main(void) {
    struct node *list = NULL;
    list = push(list, 10);
    list = push(list, 20);
    list = push(list, 30);

    int sum = 0;
    for (struct node *cur = list; cur != NULL; cur = cur->next) {
        sum += cur->value;
    }
    printf("sum = %d\n", sum);

    while (list != NULL) {
        struct node *next = list->next;
        free(list);
        list = next;
    }
    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).
print *<ptr>
Show the object a pointer refers to (p *list, p *list->next).
finish
Run until the current function returns; shows the return value.
next
Run the current line; step over function calls (n).
break <where>
Stop when execution reaches a function or line (b main, b 12).
continue
Resume until the next breakpoint or exit (c).
info breakpoints
List breakpoints and watchpoints (i b).
delete [n]
Remove breakpoint or watchpoint number n for good (d 1). With no number: remove them all.
x/<n><fmt><size> <addr>
Examine raw memory, e.g. x/4xw &values (4 hex words), x/8xb &p (8 hex bytes).

Common mistakes

Try it in your browser