# C/C++: Segmentation fault (core dumped) — SIGSEGV from a null, dangling or out-of-bounds pointer

**Code:** `Segmentation fault` · **Category:** C/C++ · **Seen on:** C/C++, Linux, GCC, Clang

The program touched memory it is not allowed to access — a null or dangling pointer, an out-of-range array index, or a stack overflow — and the OS killed it with SIGSEGV.

## Meaning

A segfault is a symptom, not a cause: the real bug can be far from the crash. Compile with `-g -fsanitize=address`, run under `gdb` and use `bt` to see the exact line. Common reasons are dereferencing `nullptr`, using memory after `free`, writing past an array, and returning a pointer to a local variable.

## Common causes

- Dereferencing a null pointer (failed `fopen`/`malloc`/`find` result not checked)
- Use after free or after the owner went out of scope
- Array or vector index out of range (`v[10]` on a 3-element vector)
- Returning a pointer or reference to a local variable
- Uninitialised pointer or infinite recursion

## Quick fix

1. Build with `-g -O0 -fsanitize=address,undefined` and re-run
2. Run `gdb ./app` then `run` and `bt`
3. Check every pointer returned by an API before using it

## Detailed fix by platform

### Linux

1. `ulimit -c unlimited` then `gdb ./app core` and type `bt`
2. `valgrind --track-origins=yes ./app` points at invalid reads and writes

### GCC / Clang

1. Compile with `g++ -g -O0 -fsanitize=address,undefined -fno-omit-frame-pointer main.cpp`

## Code examples

### Classic null dereference

```cpp
#include <cstdio>

int main() {
    FILE* f = std::fopen("missing.txt", "r");
    // if (!f) { std::perror("fopen"); return 1; }    // the missing check
    char buf[64];
    std::fgets(buf, sizeof buf, f);                    // Segmentation fault: f == nullptr
}
```

Always check the result of fopen, malloc, dynamic_cast, map::find and similar calls.

## How to diagnose

1. **Backtrace** — Which line does gdb bt show?
2. **Sanitizer** — What does AddressSanitizer report?
3. **Pointer** — Could it be null, freed or out of range?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/segmentation-fault-null-pointer)
