A buffer overflow occurs when a program writes more data to a buffer than it can hold. Because the stack stores local variables, saved registers, and return addresses in adjacent memory, overflowing a buffer can overwrite these critical values.
In a classic stack-based overflow, the attacker crafts input that is just long enough to reach the return address, then overwrites it with the address of their malicious code (shellcode). When the vulnerable function returns, instead of jumping back to the caller, execution jumps to the attacker's code.
The key vulnerability is using unsafe functions like gets(), strcpy(), or sprintf() that don't check input length. Modern defenses include stack canaries, ASLR (Address Space Layout Randomization), DEP/NX (non-executable stack), and using safe alternatives like fgets() and strncpy().
In the visualization above, notice how the "safe" input stays within the buffer boundary, while the overflow attack writes past it, corrupting the guard variable, saved frame pointer, and ultimately the return address — giving the attacker control of the program's execution.