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.