# C/C++: ==ERROR: LeakSanitizer: detected memory leaks — Direct leak of N byte(s)

**Code:** `LeakSanitizer: detected memory leaks` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

At exit, LeakSanitizer found heap blocks that were allocated but never freed and are no longer reachable.

## Meaning

The report groups leaks by allocation stack ("Direct leak" = nothing points to it; "Indirect leak" = reachable only from a leaked block). Fix the largest and most frequent first. Not every leak is a bug in short-lived tools, but in servers and loops they accumulate until `bad_alloc` or the OOM killer.

## Common causes

- `new`/`malloc` without matching `delete`/`free`
- Early return or exception between allocation and free
- Cyclic `shared_ptr` references (use `weak_ptr` for back-links)
- Container of raw owning pointers never deleted
- Third-party handle not closed (`fopen`, `dlopen`, library init)

## Quick fix

1. Replace raw `new` with `std::make_unique` / containers
2. Break `shared_ptr` cycles with `weak_ptr`
3. Run with `ASAN_OPTIONS=detect_leaks=1` and fix top stacks first

## Detailed fix by platform

### GCC / Clang

1. `g++ -g -fsanitize=address main.cpp && ASAN_OPTIONS=detect_leaks=1 ./a.out`
2. `valgrind --leak-check=full --show-leak-kinds=all ./app`

### macOS

1. LeakSanitizer is not in Apple Clang's ASan; use `leaks --atExit -- ./app` or Instruments

## Code examples

### RAII instead of new/delete

```cpp
#include <memory>
#include <vector>

struct Node { std::vector<std::unique_ptr<Node>> kids; };

int main() {
    auto root = std::make_unique<Node>();                // freed automatically at scope exit
    root->kids.push_back(std::make_unique<Node>());
    // Node* leak = new Node;                            // "Direct leak of 24 byte(s)"
}
```

## How to diagnose

1. **Stack** — Which allocation stack leaks the most?
2. **Ownership** — Who should free it?
3. **Exit** — Early returns or exceptions?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/lsan-memory-leaks)
