Segmentation Faults

What Is a Segmentation Fault in C++?

A segmentation fault is a crash that occurs when a C++ program accesses memory it isn't allowed to use. Learn the causes and how to find the bug.

On this page
  1. The short answer
  2. What the operating system is protecting
  3. What a segfault looks like
  4. A small example that crashes
  5. Why the crash can show up far from the bug
  6. Common causes
  7. How to find the line
  8. How to avoid segfaults in C++
  9. Segfault or another crash?

The short answer

A segmentation fault, often shortened to “segfault,” is a crash that happens when a C++ program tries to read or write memory it isn’t allowed to touch. The operating system stops the program, and the terminal often shows a message such as Segmentation fault (core dumped). The error happens while the program runs, so the compiler rarely flags the bug before the program starts.

What the operating system is protecting

Each running program gets its own set of memory addresses. Some of those addresses hold the program’s code, its global variables, its heap (memory requested at run time with new or malloc) and its stack (space for function calls and local variables). Other addresses aren’t mapped to anything at all, and some regions are marked read-only.

The processor’s memory hardware checks each access against these rules. If a program reads an address that isn’t mapped, or writes to a read-only region, the hardware raises a fault. The operating system then sends the process a signal called SIGSEGV, which ends the program by default. The signal itself is covered in what is SIGSEGV segmentation fault.

What a segfault looks like

The exact output depends on your system:

  • On Linux, the shell often prints Segmentation fault (core dumped). The shell reports the exit status as 139, which is 128 plus signal 11 on Linux.
  • Other Unix-like systems print similar messages, and the wording varies by shell.
  • On Windows, the same kind of error is usually reported as an access violation.
  • In an IDE debugger, the program stops at or near the line that made the bad access, which is often the fastest clue.

A small example that crashes

int main() {
    int* value = nullptr;  // Points to no valid memory
    *value = 42;           // Usually crashes on this line
    return 0;
}

Build it without optimization, so the compiler doesn’t rewrite the bad write:

g++ -g -O0 crash.cpp -o crash
./crash

On a typical Linux system, running this ends with a segmentation fault. An optimizer may treat a write through a known null pointer as impossible and change the program in unexpected ways, so keep optimization off while you hunt the bug.

Why the crash can show up far from the bug

Dereferencing a bad pointer, or going past the end of an array, is undefined behavior in C++. The language standard sets no rules for what happens next, so the program might crash right away, crash later, print wrong results or seem to work. A write just past the end of an array could silently change another variable, and the crash may happen much later, when that variable is used. This is why the line the debugger shows isn’t always the line with the mistake.

Common causes

  • Dereferencing a null pointer, or a pointer that was declared but never set
  • Using memory after it has been freed, through a dangling pointer
  • Indexing past the end of an array, vector or string
  • Runaway recursion that uses up the stack
  • Writing to read-only memory, such as a string literal

Each cause gets its own example in what can cause a seg fault. The memory regions these rules protect are described in what is segmentation with an example.

How to find the line

Most segfaults can be tracked down with a few steps:

  1. Compile with debug information and no optimization: g++ -g -O0 crash.cpp -o crash. The -g flag adds the information that lets a debugger show line numbers. The same setup is explained in how to compile a C program for GDB.
  2. Run the program under gdb: gdb ./crash, then type run. When the crash happens, gdb reports Program received signal SIGSEGV and shows the line. Type bt to see the chain of function calls that led there.
  3. Run a memory checker. Valgrind’s memcheck tool reports invalid reads and writes with line numbers, which helps when the crash happens long after the bad access. For a fuller walkthrough, see how to use valgrind in c.
  4. Build with AddressSanitizer while testing: g++ -g -fsanitize=address crash.cpp -o crash. It stops at the first bad access and prints a stack trace. It slows the program down and uses more memory, so keep it for testing rather than production.

How to avoid segfaults in C++

  • Prefer std::vector, std::string and std::array to raw arrays. Their at() member checks the index and throws std::out_of_range instead of reading past the end.
  • Use std::unique_ptr or std::shared_ptr instead of raw new and delete where you can. std::make_unique creates a std::unique_ptr for you.
  • Give every variable and pointer a value when you declare it.
  • Check a pointer against nullptr before using it, especially when a function may return null.
  • Compile with -Wall -Wextra and read the warnings.
  • Run tests with AddressSanitizer or Valgrind so bad accesses are caught before release.

Segfault or another crash?

Several errors look similar. An abort (SIGABRT) happens when a program calls abort() or when the runtime detects serious damage, such as a double free. A bus error (SIGBUS) is a related signal, usually tied to misaligned access or to memory-mapped files. On Linux, a stack overflow usually shows up as a segmentation fault too.

A segfault always means the program touched memory it shouldn’t have. Start by checking the pointers and indexes on the line the debugger shows, then confirm the real bug with gdb, Valgrind or AddressSanitizer.

Keep exploring

Guides from other topics

All topics →

Enums in C++ With Examples

Learn enums in C++ with clear examples: syntax, automatic values, enum class, switch statements, underlying types, and common mistakes to avoid.

Enums 5 min read