Skip to content

Exploring Buffer Overflows in C

Posted on:September 21, 2025

I was studying Rust’s bounds checks and their performance cost. To understand the safety trade offs, I experimented with stack based buffer overflows in C.


Minimal Example

#include <stdio.h>

int main() {
    char buffer[16];
    printf("Enter some text: ");
    gets(buffer);  // unsafe
    printf("You entered: %s\n", buffer);
    return 0;
}

Compile

c -fno-stack-protector -z execstack -g overflow.c -o overflow

Run & Crash

Enter some text: AAAAAAAAAAAAAAAAAA
You entered: AAAAAAAAAAAAAAAAAA
Segmentation fault (core dumped)

Stack layout:

[ higher ]
| return address | <- overwritten
| saved frame    |
| buffer[16]     | <- input
[ lower ]

Monitor with GDB

gdb ./overflow
(gdb) break main
(gdb) run
(gdb) next
**(gdb) x/32x $rsp**

Safe Function Pointer Experiment

void (*func_ptr)() = NULL;

Memory layout:

+------------+----------+
| buffer[16] | func_ptr |
+------------+----------+
Input: "AAAAAAAA" + function_address

Key Takeaways