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
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.
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.
print <expr>print *<ptr>finishnextbreak <where>continueinfo breakpointsdelete [n]x/<n><fmt><size> <addr>print *n before the malloc line has run. n is uninitialised there; the result is meaningless or an error. Step past the line first.continue keeps stopping in push. That breakpoint is still set. info breakpoints shows its number; delete 1 removes it.free, the bytes may still be readable. The debugger shows memory, not ownership.