# C/C++: ==ERROR: AddressSanitizer: heap-use-after-free on address — memory used after delete/free

**Code:** `AddressSanitizer: heap-use-after-free` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

The program read or wrote a heap block after it had been freed; ASan shows who freed it and where it was allocated.

## Meaning

Use-after-free is a leading cause of security bugs. The report has three stacks: the bad access, the `freed by thread T0 here` stack, and the `previously allocated by` stack. Typical cases are iterators or references into a `std::vector` that reallocated, a raw pointer outliving its owner, and callbacks capturing `this` of a deleted object.

## Common causes

- Using a pointer after `delete`/`free`
- Holding a reference, pointer or iterator into a container that was resized or erased
- Callback or thread using an object that has been destroyed
- Returning `.c_str()`/`.data()` of a temporary string
- Two owners where one deletes

## Quick fix

1. Compare the access stack with the "freed by" stack
2. Replace raw owning pointers with `unique_ptr`/`shared_ptr`
3. Don't keep references or iterators across insertions

## Detailed fix by platform

### GCC / Clang

1. Build with `-fsanitize=address -g` and run the failing case; set `ASAN_OPTIONS=detect_stack_use_after_return=1` for stack variants

### Linux

1. `valgrind ./app` prints "Invalid read of size 4 ... Address is 0 bytes inside a block of size 40 free'd"

## Code examples

### Dangling iterator

```cpp
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3};
    int& first = v[0];
    v.push_back(4);          // may reallocate -> 'first' now points to freed memory
    return first;            // heap-use-after-free READ of size 4
    // fix: copy the value (int first = v[0];) or use indices
}
```

## How to diagnose

1. **Access** — Where is the freed memory touched?
2. **Free** — Which line freed it?
3. **Owner** — Who is supposed to own this object?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/asan-heap-use-after-free)
