https://jvns.ca/blog/2021/05/17/how-to-look-at-the-stack-in-gdb/?utm_source=hackernewsletter&utm_medium=email&utm_term=code

I was chatting with someone yesterday and they mentioned that they don’t really understand exactly how the stack works or how to look at it.

So here’s a quick walkthrough of how you can use gdb to look at the stack of a C program. I think this would be similar for a Rust program, but I’m going to use C because I find it a little simpler for a toy example and also you can do Terrible Things in C more easily.

our test program

Here’s a simple C program that declares a few variables and reads two strings from standard input. One of the strings is on the heap, and one is on the stack.

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

int main() {
    char stack_string[10] = "stack";
    int x = 10;
    char *heap_string;

    heap_string = malloc(50);

    printf("Enter a string for the stack: ");
    gets(stack_string);
    printf("Enter a string for the heap: ");
    gets(heap_string);
    printf("Stack string is: %s\\n", stack_string);
    printf("Heap string is: %s\\n", heap_string);
    printf("x is: %d\\n", x);
}

This program uses the extremely unsafe function gets which you should never use, but that’s on purpose – we learn more when things go wrong.

step 0: compile the program.

We can compile it with gcc -g -O0 test.c -o test.

The -g flag compiles the program with debugging symbols, which is going to make it a lot easier to look at our variables.

step 1: start gdb

We can start gdb like this:

$ gdb ./test

It prints out some stuff about the GPL and then gives a prompt. Let’s create a breakpoint on the main function.

(gdb) b main
Breakpoint 1 at 0x1171: file test.c, line 4.

Then we can run the program:

(gdb) run
Starting program: /home/bork/work/homepage/test

Breakpoint 1, main () at test.c:4
4	int main() {

Okay, great! The program is running and we can start looking at the stack