MiddleDebuggingCommonNot answered yet
What happens if you write more data than you allocated (buffer overflow)?
This function copies a name into a fixed-size buffer. With a long input the program corrupts memory, crashes, or — worse — silently keeps running.
void store(const char* name) {
char buf[16];
std::strcpy(buf, name);
std::cout << buf << '\n';
}
Identify the bug and explain the cause.
Writing past the allocated region corrupts adjacent memory: on the stack this overwrites the return address (stack smashing); on the heap it corrupts allocator metadata. Detect with AddressSanitizer, Valgrind, or stack canaries.
- ✗Using C-style
strcpy/getswithout size checks — these functions are the most common source of stack buffer overflows - ✗Allocating
nbytes but writingn+1(null terminator) — classic off-by-one in string handling - ✗Thinking
std::stringandstd::vectorprevent all overflows — incorrect bounds in manual indexing (operator[]) still overflow
- →What is ASLR and how does it make buffer overflow exploits harder but not impossible?
- →How do stack canaries detect stack buffer overflows?