# C/C++: *** stack smashing detected ***: terminated — buffer overflow on the stack

**Code:** `stack smashing detected` · **Category:** C/C++ · **Seen on:** C/C++, Linux, GCC

GCC's stack protector noticed that a local buffer overflowed and overwrote the function's canary value, so it aborted the program.

## Meaning

When a function returns, the guard value placed after its local arrays is checked. A write past the end of a `char buf[16]` (from `strcpy`, `gets`, `scanf("%s")`, `sprintf` or an off-by-one loop) changes it, producing this abort. The crash is reported at function exit, not at the faulty write.

## Common causes

- `strcpy`, `sprintf`, `gets` or `scanf("%s")` into a fixed-size array
- Loop with `<=` instead of `<` writing one element past the end
- Wrong buffer length passed to `read`/`memcpy`
- Format specifier mismatch writing more bytes than expected

## Quick fix

1. Use bounded functions: `snprintf`, `strncpy` (carefully), `fgets`, or `std::string`
2. Compile with `-fsanitize=address -g` to see the exact overflowing write
3. Check every length argument

## Detailed fix by platform

### GCC / Clang

1. `g++ -g -fsanitize=address main.cpp -o app` — AddressSanitizer names the line with "stack-buffer-overflow"
2. Use `-Wall -Wformat-overflow -Wstringop-overflow` for compile-time hints

## Code examples

### Bounded copy

```cpp
#include <cstdio>
#include <cstring>

int main() {
    char name[8];
    const char* input = "Alexander";
    // std::strcpy(name, input);                 // 10 bytes into 8: stack smashing
    std::snprintf(name, sizeof name, "%s", input);   // truncates safely to "Alexand"
    std::puts(name);
}
```

## How to diagnose

1. **ASan** — Which line does stack-buffer-overflow name?
2. **Buffers** — Fixed-size local arrays written to?
3. **Loops** — Any <= bound?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/stack-smashing-detected)
