# C/C++: ==ERROR: AddressSanitizer: heap-buffer-overflow on address — READ/WRITE of size N

**Code:** `AddressSanitizer: heap-buffer-overflow` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

AddressSanitizer caught a read or write just outside a heap block — an array index or length that is off by one or more.

## Meaning

ASan places "red zones" around every heap allocation. The report gives the access type and size, the stack of the faulty access, and where the block was allocated. Typical sources are `<=` loop bounds, forgetting the trailing NUL of C strings, wrong `memcpy` lengths and `std::vector::operator[]` past `size()`.

## Common causes

- Loop `i <= n` or `i < n + 1` over an array of n elements
- C string buffer without space for the terminating `\0`
- `memcpy`/`memset` with a wrong byte count (elements vs bytes)
- `vector[index]` beyond size or after reallocation
- Using `malloc(strlen(s))` instead of `strlen(s) + 1`

## Quick fix

1. Read the first stack frame in "READ/WRITE of size" — that is the bad access
2. Compare it with the allocation stack ("allocated by thread T0 here")
3. Fix the bound and re-run with ASan until clean

## Detailed fix by platform

### GCC / Clang

1. `g++ -g -O1 -fsanitize=address -fno-omit-frame-pointer main.cpp -o app && ./app`
2. `ASAN_OPTIONS=symbolize=1:detect_leaks=1 ./app`

### CMake

1. `target_compile_options(app PRIVATE -fsanitize=address -fno-omit-frame-pointer)` and `target_link_options(app PRIVATE -fsanitize=address)`

## Code examples

### Off-by-one

```cpp
#include <cstring>
#include <cstdlib>

int main() {
    const char* s = "hello";
    char* copy = static_cast<char*>(std::malloc(std::strlen(s)));       // no room for '\0'
    std::strcpy(copy, s);                                                // heap-buffer-overflow WRITE of size 6
    std::free(copy);
    // fix: std::malloc(std::strlen(s) + 1)
}
```

## How to diagnose

1. **Access** — READ or WRITE, and what size?
2. **Block** — How big is the allocation?
3. **Bound** — Which index or length is wrong?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/asan-heap-buffer-overflow)
