Heap buffer overflows
What you'll learn: How writing past the end of allocated memory on the heap can corrupt data and crash your program.
The guest list analogy
Imagine you rent a small VIP booth at a club that holds exactly 4 people. You give the manager your credit card, and they mark off seats 10, 11, 12, and 13 for your group. Everything is fine until a 5th person shows up. Instead of renting another booth, you force them to sit in seat 14.
The problem? Seat 14 belongs to a different group—or worse, it’s where the manager keeps the cash register. By sitting where you weren't invited, you’ve interfered with someone else's space. In C, the heap is that club, malloc() is your reservation, and sitting in seat 14 is a heap buffer overflow.
Color outside the lines
When you allocate memory using malloc(), the computer gives you a starting address and reserves a specific number of bytes just for you. However, C is a "trusting" language. It won't stop you if you try to write to the 11th byte of a 10-byte reservation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Reserve space for 8 characters
char *username = malloc(8 * sizeof(char));
// Attempting to cram 15 characters into an 8-byte space
// This "overflows" the buffer and spills into adjacent memory
strcpy(username, "SuperLongAdminName");
printf("Username: %s\n", username);
free(username);
return 0;
}
In the example above, strcpy doesn't check if username is big enough. It blindly writes "SuperLongAdminName" into the heap. Since we only asked for 8 bytes, the extra letters spill over, overwriting whatever was stored next to our buffer.
Why it’s dangerous
Heap overflows are particularly nasty because they are silent. Your program might not crash immediately. Instead, it might overwrite a variable used elsewhere, causing a "teleporting" bug where data changes randomly in a completely different part of your code. In professional software, hackers use this trick to overwrite function pointers, redirecting the program to run their own malicious code.
Always ensure your logic respects the boundaries of the memory you requested. If you need more space, use realloc() or check the length of your data before copying it.
Key takeaway
A heap buffer overflow occurs when you write more data than a malloc block can hold, corrupting neighboring memory and causing unpredictable behavior.