Real examples of segmentation faults: Stack Overflow examples and how to fix them

If you write C, C++, Rust with unsafe, or low-level code in general, segmentation faults are your rite of passage. You hit run, your program crashes, and you’re staring at `Segmentation fault (core dumped)` wondering what just happened. That’s where real examples of segmentation faults: Stack Overflow examples in particular, become incredibly useful. They show the patterns behind these crashes, not just the one-off bugs. In this guide, we’ll walk through concrete examples of segmentation faults: Stack Overflow examples pulled from the kinds of questions developers ask every day. We’ll look at out-of-bounds access, stack overflow from runaway recursion, use-after-free, null pointers, and more. For each example of a segfault pattern, you’ll see the broken code, why it fails at the memory level, and how to fix it in a way that would actually pass code review. Think of this as a field guide to the bugs that keep systems engineers awake at night.
Written by
Jamie
Published
Updated

When developers search for examples of segmentation faults: Stack Overflow examples dominate the results for a reason: they capture what people actually break in day‑to‑day code. Patterns repeat. Once you recognize those patterns, you start seeing bugs before they ship.

Below, we’ll walk through several realistic scenarios that mirror the best examples people post on Stack Overflow: short, painful, and instantly recognizable if you’ve ever debugged C or C++.


Classic example of stack overflow causing a segmentation fault

Let’s start with the namesake: a stack overflow that triggers a segmentation fault.

// naive_factorial.c
long long fact(long long n) {
    // Missing base case for n < 0
    if (n == 0) return 1;
    return n * fact(n - 1);
}

int main(void) {
    // User accidentally passes a negative value
    long long n = -5;
    long long result = fact(n);
    return 0;
}

This is one of the best examples of segmentation faults you’ll see in beginner code. The logic looks fine at a glance, but when n is -5, the recursion runs fact(-5), fact(-6), fact(-7)… forever. Each call pushes a new stack frame. Eventually, the call stack grows beyond the memory region reserved for it and the OS raises a segmentation fault.

On Linux, you can even inspect the default stack size with ulimit -s. Once your recursion depth exceeds that limit, you’re done.

Fix: add a proper base case and input validation:

long long fact(long long n) {
    if (n < 0) {
        fprintf(stderr, "Negative input not allowed\n");
        exit(EXIT_FAILURE);
    }
    if (n == 0) return 1;
    return n * fact(n - 1);
}

This is exactly the kind of pattern you see in real examples of segmentation faults: Stack Overflow examples are full of runaway recursion that nobody thought to bound.


Out-of-bounds arrays: the most common example of segmentation faults

If you search for examples of segmentation faults: Stack Overflow examples, you’ll see a flood of questions that look like this:

int main(void) {
    int arr[5];
    for (int i = 0; i <= 5; ++i) {
        arr[i] = i * 10;   // BUG: i == 5 writes past the end
    }
    return 0;
}

The bug is tiny: <= 5 instead of < 5. But that off‑by‑one turns into a write beyond the array boundary. Whether you get a segmentation fault depends on what lives next in memory and how your compiler laid things out.

Why it sometimes “works” in debug builds
With optimizations off, the memory layout is often more forgiving. The write may silently corrupt some padding or another local variable. Turn on optimizations, or change the code slightly, and the same program suddenly segfaults. That’s why these are some of the best examples to study: they show how undefined behavior can appear nondeterministic.

Safer pattern:

#define ARRAY_LEN(x) (sizeof(x) / sizeof((x)[0]))

int main(void) {
    int arr[5];
    size_t n = ARRAY_LEN(arr);
    for (size_t i = 0; i < n; ++i) {
        arr[i] = (int)(i * 10);
    }
    return 0;
}

A lot of Stack Overflow answers to these examples of segmentation faults recommend using std::vector in C++ or bounds‑checked containers in higher‑level languages to avoid this entire category of bug.


Null pointer dereference: tiny mistake, instant crash

Another recurring example of a segmentation fault looks like this:

struct Node {
    int value;
    struct Node *next;
};

void print_value(struct Node *node) {
    printf("%d\n", node->value);   // Potential null dereference
}

int main(void) {
    struct Node *head = NULL;
    print_value(head);              // Segmentation fault
    return 0;
}

Here, head is NULL, but the code blindly dereferences node->value. On most modern OSes, address 0 (or very low addresses) are not mapped into the process address space, so dereferencing a null pointer triggers a segmentation fault.

Better pattern: always validate inputs at the boundary:

void print_value(struct Node *node) {
    if (!node) {
        fprintf(stderr, "Node is NULL\n");
        return;
    }
    printf("%d\n", node->value);
}

If you browse real examples of segmentation faults: Stack Overflow examples, you’ll see this pattern constantly in list handling, tree traversal, and error paths that weren’t fully tested.


Use-after-free: the silent memory time bomb

Use‑after‑free bugs are nastier because they don’t always crash immediately. But when they do, they often show up as segmentation faults that are hard to reproduce.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *make_message(void) {
    char *buf = malloc(16);
    strcpy(buf, "Hello");
    return buf;
}

int main(void) {
    char *msg = make_message();
    free(msg);

    // BUG: use-after-free
    printf("%s\n", msg);      // Sometimes prints, sometimes segfaults

    return 0;
}

After free(msg), the pointer is dangling. The memory may be reused by the allocator or protected in a way that causes a segmentation fault on access. On some platforms, hardened allocators purposely poison freed memory to turn these into visible crashes instead of silent corruption.

Safer habit:

free(msg);
msg = NULL;   // Avoids accidental reuse

Modern tools like AddressSanitizer (ASan) are widely recommended in Stack Overflow answers to these examples of segmentation faults. ASan can detect use‑after‑free, out‑of‑bounds access, and other memory violations with clear error reports.

For an in‑depth look at memory safety research, the US National Institute of Standards and Technology (NIST) maintains resources on software assurance and memory safety issues at nist.gov.


Stack vs heap confusion: local buffers returned by address

One of the best examples of segmentation faults that keeps reappearing is returning a pointer to a local stack variable:

char *get_name(void) {
    char buffer[32];
    scanf("%31s", buffer);
    return buffer;    // BUG: returning pointer to stack memory
}

int main(void) {
    char *name = get_name();
    printf("%s\n", name);   // Undefined behavior, often segfaults
    return 0;
}

buffer lives on the stack. Once get_name returns, that stack frame is gone; the pointer now refers to memory that can be reused for something else. Accessing it later may cause a segmentation fault or print garbage.

Correct approach: allocate on the heap or have the caller provide the buffer:

char *get_name(void) {
    char *buffer = malloc(32);
    if (!buffer) return NULL;
    scanf("%31s", buffer);
    return buffer;   // Caller must free
}

Real examples of segmentation faults: Stack Overflow examples around this pattern are often answered with a short lecture on stack vs heap lifetime and why automatic storage duration cannot safely be returned by address.


Writing through uninitialized pointers

Sometimes the pointer itself is uninitialized, not just null. That’s even more dangerous:

int main(void) {
    int *p;           // Uninitialized

    *p = 42;          // Write to random address → likely segfault
    return 0;
}

Here p contains garbage. Writing through it is a write to some arbitrary address in the process’s virtual address space. If the address is unmapped or protected, you get a segmentation fault. If it happens to land in writable memory, you get silent corruption instead.

Static analysis tools like clang-tidy, cppcheck, and commercial analyzers are often recommended in answers to these examples of segmentation faults to catch uninitialized variables before they hit production.


Multi-threaded race conditions leading to segmentation faults

As systems get more concurrent, a lot of modern examples of segmentation faults: Stack Overflow examples involve threads and data races. Consider this simplified case:

#include <pthread.h>
#include <stdlib.h>

int *shared_ptr;

void *worker1(void *arg) {
    shared_ptr = malloc(sizeof(int));

    *shared_ptr = 123;
    return NULL;
}

void *worker2(void *arg) {
    // No synchronization: may run before allocation

    *shared_ptr = 456;    // Potential segfault if shared_ptr is NULL or garbage
    return NULL;
}

int main(void) {
    pthread_t t1, t2;
    pthread_create(&t1, NULL, worker1, NULL);
    pthread_create(&t2, NULL, worker2, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    free(shared_ptr);
    return 0;
}

Without proper synchronization, worker2 might run before worker1 initializes shared_ptr. Writing through an uninitialized or null pointer is back to our earlier examples: undefined behavior, often a segmentation fault.

Thread sanitizers (TSan) and correct use of mutexes or atomics are the typical prescriptions you’ll see in Stack Overflow answers to these concurrent segmentation fault questions.


How to debug segmentation faults effectively in 2024–2025

Looking at real examples of segmentation faults: Stack Overflow examples is useful, but you also need a repeatable way to diagnose your own crashes. The tooling story has improved a lot over the last decade.

Use a debugger
On Linux and macOS, gdb and lldb are still the go‑to tools:

gcc -g -O0 bug.c -o bug
./bug   # program crashes

## Then
gdb ./bug core
(gdb) bt   # backtrace

You’ll see the call stack at the moment of the segmentation fault, including the line number.

Use sanitizers
Modern compilers ship with powerful runtime checks:

gcc -g -fsanitize=address -fno-omit-frame-pointer bug.c -o bug
./bug

AddressSanitizer produces detailed reports for many of the examples of segmentation faults we’ve discussed: out‑of‑bounds, use‑after‑free, stack overflow, and more.

Adopt safer languages where possible
A lot of current research and industry guidance, including work discussed by US government and academic organizations, points toward memory‑safe languages as a way to reduce entire classes of segmentation faults. The US Cybersecurity and Infrastructure Security Agency (CISA) and partners have discussed memory safety in secure coding guidance at cisa.gov and related resources.

Rust, modern C++ with RAII and smart pointers, and managed languages like Java and C# all reduce your exposure to raw pointer errors. They don’t eliminate all bugs, but they significantly cut down on the kind of real examples of segmentation faults: Stack Overflow examples we’ve been walking through.

For a broader perspective on software reliability and safety‑critical systems, you can explore materials from universities such as MIT OpenCourseWare, which often cover debugging, testing, and formal methods.


FAQ: common questions and examples of segmentation faults

What are the most common examples of segmentation faults in C and C++?

The most common examples of segmentation faults in C and C++ include:

  • Accessing arrays out of bounds (off‑by‑one errors in loops)
  • Dereferencing null or uninitialized pointers
  • Returning pointers to stack‑allocated variables
  • Use‑after‑free on heap allocations
  • Infinite or very deep recursion causing stack overflow
  • Data races in multi‑threaded code that lead to invalid pointer access

If you browse Stack Overflow, these patterns account for the majority of “why am I getting a segmentation fault?” questions.

Can a stack overflow always cause a segmentation fault?

A stack overflow often leads to a segmentation fault, but the exact behavior depends on the operating system and how the stack is mapped. Most modern OSes place a guard page at the end of the stack region; when your program’s stack pointer crosses into that page, you get a segmentation fault. Some environments may instead abort with another signal or error, but from a developer’s perspective, a stack overflow is one of the most reliable examples of segmentation faults in recursive code.

How can I find the exact line that triggered the segmentation fault?

Compile with debug symbols (-g for gcc/clang), reproduce the crash, and then use a debugger (gdb, lldb, or Visual Studio’s debugger). Load the core dump or attach to the running process, then inspect the backtrace. Many answers to examples of segmentation faults: Stack Overflow examples walk through this process step by step, because once you have a backtrace, you can see the exact function and line that accessed invalid memory.

Is it possible to recover from a segmentation fault inside the program?

In general, no. A segmentation fault means your program has already performed an invalid memory access, and its internal state may be corrupted. While some advanced systems use signal handlers to log details or attempt limited cleanup, the typical guidance from both industry and academic sources is to treat a segfault as a fatal error, fix the bug, and redeploy rather than trying to continue execution.

Where can I see more real examples of segmentation faults and fixes?

Stack Overflow remains the best public archive of real examples of segmentation faults, with thousands of questions tagged segmentation-fault and c or c++. For deeper background on safe coding practices and memory safety, US government and academic resources such as NIST, CISA, and university courseware (for example, MIT OpenCourseWare) provide broader context and training material.

Studying those real examples of segmentation faults: Stack Overflow examples, combined with disciplined use of debuggers and sanitizers, is still one of the fastest ways to level up your low‑level debugging skills.

Explore More Segmentation Faults

Discover more examples and insights in this category.

View All Segmentation Faults