Buffer overflows via pointers
What you'll learn: How to prevent pointers from accidentally writing data outside the boundaries of an array.
The "Boundary" Problem
Imagine you have a row of ten lockers in a hallway. You are given a key (a pointer) to the first locker and told to put a book in every locker starting from the first one. If you count correctly, everything is fine. But if you lose track and try to put an eleventh book into a "locker" that doesn't exist, you might end up smashing it through a nearby window or shoving it into a high-voltage electrical box.
In C, pointers don't know how much memory they are allowed to touch. They simply point to an address and move forward when you tell them to. A buffer overflow happens when a pointer moves past the end of its assigned "buffer" (like an array) and starts writing data into memory it doesn't own.
Why it's dangerous
When a pointer overflows, it doesn't always cause an immediate crash. Instead, it might overwrite:
- Other variables: Suddenly, your
user_agevariable changes to9999because a nearby pointer leaked into its space. - Return addresses: Hackers use this to redirect a program to run malicious code.
- System memory: This usually results in the dreaded "Segmentation Fault."
Seeing it in action
In the example below, we have a small array. Watch how a pointer can easily "go rogue" if we don't check our limits.
#include <stdio.h>
int main() {
int numbers[3] = {10, 20, 30};
int *ptr = numbers;
// Moving the pointer within bounds
for (int i = 0; i < 3; i++) {
printf("Value at index %d: %d\n", i, *(ptr + i));
}
// DANGER: Moving the pointer outside the buffer
// There is no index 3, but the pointer will try to access it anyway.
int *rogue_ptr = ptr + 3;
// This writes to memory we don't own!
*rogue_ptr = 999;
printf("Overflowed value: %d\n", *rogue_ptr);
return 0;
}
How to stay safe
Because C won't stop you from crossing the finish line, you must be the referee. Always track the size of your buffers. Before you use a pointer to write data (*ptr = value), ensure the address it currently holds is still within the original array's starting and ending memory addresses.
Key takeaway
A pointer is just an address; it has no built-in knowledge of array limits, so you must manually ensure it never writes beyond the buffer's end.