Buffer Overflow Attacks Explained and How Secure Coding Prevents Them

A buffer overflow happens when a program writes more data into a memory buffer than it can hold, overwriting adjacent memory. In languages like C and C++ that do not check bounds automatically, attackers can use overflows to crash programs or redirect execution to their own code.

Jul 18, 2025 - 16:52
Updated: 
102.8k

Web & API Security in Cybersecurity & Ethical Hacking · Tutorial

Penetration Testing

Buffer Overflow Attacks Explained and How Secure Coding Prevents Them

Quick answer: A buffer overflow happens when a program writes more data into a memory buffer than it can hold, overwriting adjacent memory. In languages like C and C++ that do not check bounds automatically, attackers can use overflows to crash programs or redirect execution to their own code. Prevention combines secure coding (bounds-checked functions, input length validation), compiler and operating system protections (stack canaries, ASLR, non-executable memory, control-flow integrity), testing with sanitizers and fuzzing, and, increasingly, writing new code in memory-safe languages such as Rust, Go, Java or C#.

Key takeaways

  • Out-of-bounds writes (CWE-787) consistently rank among the most dangerous software weaknesses.
  • Unsafe C functions such as strcpy and gets are common causes.
  • OS and compiler mitigations make exploitation harder but not impossible.
  • AddressSanitizer and fuzzing find overflows before release.
  • CISA and partner agencies urge vendors to adopt memory-safe languages.

Table of Contents

What Is a Buffer Overflow?

Programs store data in fixed-size buffers. If code copies input into a buffer without checking its length, extra bytes spill into neighbouring memory, which may hold other variables, function return addresses or heap metadata. Changing these can crash the program or, in the worst case, let an attacker control what runs next. MITRE tracks this as CWE-787, a regular entry near the top of the CWE Top 25.

What Types Exist?

TypeCWEDescription
Stack-basedCWE-121Overflow of local variables on the call stack
Heap-basedCWE-122Overflow of dynamically allocated memory
Integer overflow leading to overflowCWE-190Wrong size calculation allocates too little memory
Off-by-oneCWE-193Writing one byte past the end

What Does Vulnerable and Safe Code Look Like?

/* Vulnerable: no length check */
void greet(const char *name) {
    char buf[32];
    strcpy(buf, name);          /* overflows if name is 32+ characters */
    printf("Hello %s\n", buf);
}

/* Safer: bounded copy and explicit termination */
void greet_safe(const char *name) {
    char buf[32];
    snprintf(buf, sizeof buf, "%s", name);   /* truncates safely */
    printf("Hello %s\n", buf);
}

The SEI CERT C Coding Standard lists rules for string and memory handling.

Which Mitigations Help?

MitigationWhat it does
Stack canariesDetect overwritten stack frames before returning
DEP / NXMark data memory non-executable
ASLRRandomise memory addresses so targets are hard to predict
Control-flow integrityRestrict where indirect calls may go, such as Windows Control Flow Guard
FORTIFY_SOURCEAdds bounds checks to common library calls
# Compile with common hardening flags (GCC/Clang)
gcc -O2 -fstack-protector-strong -D_FORTIFY_SOURCE=3 -fPIE -pie -Wl,-z,relro,-z,now -o app app.c

How Do You Find Overflows?

# Build with AddressSanitizer and run tests; it reports out-of-bounds accesses
clang -g -fsanitize=address -o app_asan app.c && ./app_asan "$(python3 -c 'print("A"*100)')"

# Fuzz a parsing function with libFuzzer
clang -g -fsanitize=fuzzer,address -o fuzz_parser fuzz_parser.c && ./fuzz_parser

AddressSanitizer pinpoints the faulty line. Static analysers (Clang Static Analyzer, CodeQL) also flag risky patterns.

Why Move to Memory-Safe Languages?

Memory-safe languages check bounds automatically, eliminating this whole class of bug. In December 2023, CISA, NSA and international partners published The Case for Memory Safe Roadmaps, urging software makers to plan transitions. Practical steps: write new components in Rust, Go, C# or Java; isolate legacy C/C++ in sandboxes; and prioritise rewriting code that parses untrusted input. Related: common application attacks. WebAsha offers secure coding training.

References

Frequently Asked Questions

Writing more data into a memory buffer than it can hold, overwriting adjacent memory.

They do not check array bounds automatically, so programmers must do it manually.

Stack overflows affect local variables and return addresses; heap overflows affect dynamically allocated memory.

ASLR randomises memory addresses and DEP makes data memory non-executable, both making exploitation harder.

With AddressSanitizer, fuzzing, static analysis and code review.

Functions like gets, strcpy and sprintf without bounds; use snprintf and bounded alternatives.

Yes. Languages such as Rust, Go, Java and C# check bounds and prevent this class of bug.

CISA and partners urged software makers to publish memory-safe roadmaps and adopt memory-safe languages.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Vaishnavi

Vaishnavi is a skilled tech professional at the Ethical Hacking Training Institute in Pune, responsible for managing and optimizing the technical infrastructure that supports advanced cybersecurity education. With deep expertise in network security, backend operations, and system performance, she ensures that practical labs, online modules, and assessments run smoothly and securely. Her behind-the-scenes contributions play a vital role in delivering a seamless and secure learning experience for aspiring ethical hackers.