CodeBlanks Logo Icon CodeBlanks

Buffer overflow

Learn the buffer overflow vulnerability.

What is a buffer overflow?

A buffer overflow happens when a write goes past an array's bounds. It is a common security flaw, especially with unbounded functions like strcpy and gets.

C arrays do no bounds checking; writing a ninth byte to char buf[8] is a memory error the compiler cannot catch. In a stack overflow an attacker can overwrite the return address and hijack control flow. That is why modern compilers add protections like canary and ASLR. Safe functions (fgets, strncpy) take an explicit size.

Stack layout and return address

On a function call the stack holds local variables, saved registers and the return address, in that order. A buffer overflow breaks this layout.

If a local array overflows, the next bytes overwrite other variables, then the return address. An attacker replacing it with a malicious address makes the function jump there on return. This is why strncpy replaces strcpy and fgets replaces gets. The compiler's -fstack-protector option places a random canary before the return address; on return, a mismatch stops the program.

Practice Check buffer bounds

Define void check_buf(const char *name, int size, int used). If used > size, print printf("%s: OVERFLOW\n", name);; otherwise print printf("%s: OK\n", name);. In main call it three times: ("buf", 8, 5), ("input", 16, 16), ("dst", 4, 8).

Starter code

main.c
#include <stdio.h>

// Define check_buf function
// Call it for buf, input, dst with (name, size, used)

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

void check_buf(const char *name, int size, int used) {
    if (used > size) {
        printf("%s: OVERFLOW\n", name);
    } else {
        printf("%s: OK\n", name);
    }
}

int main(void) {
    check_buf("buf", 8, 5);
    check_buf("input", 16, 16);
    check_buf("dst", 4, 8);
    return 0;
}

Expected output

buf: OK
input: OK
dst: OVERFLOW

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does a buffer overflow occur?

  • When the CPU is fast
  • When memory is empty
  • When a buffer bound is exceeded Correct answer
  • When a file is closed

Explanation: Writing past the array's capacity causes an overflow.

2 Complete the unsafe strcpy call

Question
char buf[8]; strcpy(buf, ____);
Answer
char buf[8]; strcpy(buf, input);

Explanation: strcpy does no bounds check; if input is longer than 8 bytes it overflows.

3 Match stack concepts

Term Meaning
buffer Buffer
stack Stack
return address Return address
overflow Overflow

All lessons in Expert