Real-world examples of segmentation fault examples: null pointer dereference

If you write C, C++, Rust unsafe blocks, or low-level Go, you’ve almost certainly met the classic bug that crashes your program with a segmentation fault: the null pointer dereference. Developers search for **examples of segmentation fault examples: null pointer dereference** because this is one of the most common and frustrating memory errors in systems programming. It shows up in production logs, in online judges, and in every intro systems course, yet it still bites experienced engineers. In this guide, we’ll walk through realistic, modern examples of how null pointer dereferences happen in 2024-era codebases: from REST services in C++ to plugin systems, FFI boundaries, and multithreaded code. We’ll look at how different operating systems handle the fault, how modern compilers and sanitizers help you catch it, and what patterns actually prevent these bugs. Instead of toy one-liners, you’ll see practical scenarios that mirror what you’re likely to debug in real projects, along with strategies to avoid repeating the same mistake.
Written by
Jamie
Published

Fast tour of real examples before theory

Let’s start the way you actually meet this bug: in code that looks fine until it explodes. Here are several real-world flavored examples of segmentation fault examples: null pointer dereference you’ll recognize from everyday development:

  • A C web service that trusts a JSON field and dereferences a pointer from it without validation.
  • A C++ plugin system that calls a virtual method on an object that was never constructed.
  • A multithreaded cache that frees an entry while another thread still uses the pointer.
  • A Rust library using unsafe to call a C function that returns NULL on error, but the Rust side assumes it’s always valid.
  • A Go program that uses unsafe.Pointer to interact with C and passes a nil pointer into a C API.

All of these are examples of the same fundamental problem: your code tried to access memory at address 0 (or very near it), and the operating system responded with a segmentation fault.


Classic C example of null pointer dereference

The most textbook example of a null pointer dereference looks something like this in C:

#include <stdio.h>

int main(void) {
    int *p = NULL;      // pointer explicitly set to null

    *p = 42;            // write through null pointer → segmentation fault
    printf("%d\n", *p);
    return 0;
}

On Linux, this usually produces Segmentation fault (core dumped). On macOS, you might see something like Segmentation fault: 11. The OS refuses to let user programs read or write address 0, so dereferencing p immediately triggers a crash.

As simple as it is, this is still one of the best examples to demonstrate what’s going on: the pointer value is 0x0, and the CPU tries to store 42 at that address.


Real examples of segmentation fault examples: null pointer dereference in C APIs

Production code rarely looks as obviously broken as the toy snippet. More realistic examples include misuse of APIs that return null on failure.

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

char *read_config_value() {
    FILE *f = fopen("config.txt", "r");
    if (!f) {
        return NULL;   // failure path
    }
    // ... read data, allocate buffer ...
}

int main(void) {
    char *value = read_config_value();

    // BUG: assumes value is never NULL
    printf("Config: %s\n", value);   // segmentation fault if value is NULL

    free(value);  // also undefined if value is NULL and not handled correctly
    return 0;
}

Here, read_config_value can return NULL, but the caller blindly passes it to printf with %s, which dereferences the pointer internally. This is a very common example of a null pointer dereference in server code that depends on configuration files, environment variables, or network responses.

In 2024-era C codebases, this pattern still shows up in:

  • Microservices using C-based HTTP libraries.
  • Embedded systems reading from sensors or flash storage.
  • CLI tools that assume files always exist.

Static analysis tools and sanitizers (like GCC’s -fsanitize=null and Clang’s AddressSanitizer) are now widely used in CI pipelines to catch exactly these examples of segmentation fault examples: null pointer dereference before they hit production.


C++: virtual methods, smart pointers, and null

C++ tries to help with smart pointers, but it still happily lets you call methods on null objects if you’re not careful. Consider this example of a plugin-style architecture:

#include <iostream>

class Plugin {
public:
    virtual void run() = 0;
};

Plugin* load_plugin() {
    // In reality, this might use dlopen/dlsym or a factory
    return nullptr;   // failed to load
}

int main() {
    Plugin* p = load_plugin();

    // BUG: no null check before virtual call
    p->run();         // segmentation fault: null pointer dereference

    return 0;
}

The virtual call p->run() on a null pointer is a textbook C++ example of null pointer dereference. In real systems, this often hides behind layers of abstraction:

  • A factory that returns nullptr when a feature flag is off.
  • A dependency injection container that couldn’t construct the dependency.
  • A failed dynamic load of a shared library.

Modern C++ encourages the use of std::unique_ptr and std::shared_ptr, but they don’t magically eliminate null. A std::shared_ptr<T> can absolutely be empty, and ptr->method() on an empty smart pointer is still a null pointer dereference.


Multithreading: use-after-free that looks like null

Not every segmentation fault in 2024 is a simple NULL literal. Concurrency can create pointers that become invalid and look like null-like bugs during debugging.

Imagine a shared cache in C:

struct entry {
    char *data;
};

struct entry *global_entry;

void reader_thread() {
    // No synchronization
    printf("%s\n", global_entry->data);
}

void writer_thread() {
    free(global_entry->data);
    free(global_entry);
    global_entry = NULL;  // attempt to be "safe"
}

Depending on timing, reader_thread might run after writer_thread freed global_entry but before it set the pointer to NULL. The CPU then dereferences a freed pointer. In practice, this often shows up in logs as if it were a plain null pointer dereference, and many engineers mentally group it under examples of segmentation fault examples: null pointer dereference, even though the root cause is a race.

Tools like ThreadSanitizer and AddressSanitizer (see the LLVM documentation at llvm.org) are widely used now to catch these concurrency-driven examples of memory errors.


FFI boundaries: Rust, Go, and null from C

In 2024–2025, a lot of low-level logic is being wrapped by Rust or Go and exposed as safe APIs. The weak point is always the FFI boundary.

Rust unsafe example

extern "C" {
    fn get_user_name(id: i32) -> *const libc::c_char; // returns NULL on error
}

pub fn user_name(id: i32) -> String {
    unsafe {
        let ptr = get_user_name(id);
        // BUG: assumes ptr is never null
        let c_str = std::ffi::CStr::from_ptr(ptr);  // UB if ptr is null
        c_str.to_string_lossy().into_owned()
    }
}

If get_user_name returns NULL for an unknown user, CStr::from_ptr will dereference it, causing undefined behavior and likely a segmentation fault. This is one of the more modern examples of segmentation fault examples: null pointer dereference, because it appears in otherwise memory-safe Rust code that dips into unsafe.

Go unsafe example

// #include <stdlib.h>
// char* maybe_name(int id) {
//     if (id < 0) return NULL;
//     return "alice";
// }
import "C"
import "unsafe"

func Name(id int) string {
    ptr := C.maybe_name(C.int(id))
    // BUG: assumes ptr is never nil
    return C.GoString(ptr) // segmentation fault if ptr == nil
}

Go is memory safe at the language level, but the moment you cross into C, you’re back in the land of examples of segmentation fault examples: null pointer dereference if you don’t check for null.


Modern OS behavior: why null hurts consistently

Across Linux, macOS, and Windows, user-space processes don’t get valid memory at address 0. The kernel typically maps low memory as non-accessible specifically to catch null pointer bugs. That’s why all these examples include the same symptom: instant segmentation fault on dereference.

Security research from the last decade pushed this even further. Older systems sometimes allowed mappings at low addresses, which attackers could abuse. Modern kernels harden this, making null pointer dereference both a reliability and a security concern. The U.S. Cybersecurity and Infrastructure Security Agency (CISA) regularly notes memory safety issues as a major class of vulnerabilities in their advisories: see cisa.gov for current guidance.


Patterns that create null pointer dereferences

Looking across all the examples of segmentation fault examples: null pointer dereference above, the patterns are boringly consistent:

  • Unchecked return values from allocation, I/O, or lookup functions.
  • Assuming constructors or factories never fail, especially in C++.
  • Relying on comments instead of types (e.g., “this function never returns null” with no type-level guarantee).
  • Improper lifetime management in multithreaded code.
  • Unsafe FFI boundaries where foreign functions may return null.

These patterns show up in academic code, open-source projects, and large commercial systems. University systems courses (for example, those published by MIT at mit.edu) still use null pointer dereference as a primary teaching tool for undefined behavior.


How to avoid these examples in real codebases

Preventing these bugs isn’t about memorizing every example of null pointer dereference. It’s about building habits and tooling:

Check every pointer from external input

Any pointer derived from:

  • malloc / calloc / realloc
  • File I/O or networking operations
  • Database lookups
  • Plugin or module loaders

should be validated before dereference. In C and C++, that means explicit if (!ptr) { /* handle error */ }. In Rust or Go FFI, that means treating NULL as an error and mapping it to Option or error types.

Use safer abstractions where possible

Languages like Rust and modern C++ provide non-null pointer types:

  • Rust’s NonNull<T> and references &T that cannot be null.
  • C++ guidelines that favor references over pointers when null is not allowed.

By using these, you make it impossible to express many examples of segmentation fault examples: null pointer dereference at the type level.

Turn on sanitizers in CI

In 2024–2025, it’s standard practice for serious C/C++ projects to run with:

gcc -g -O1 -fsanitize=address,null,undefined -fno-omit-frame-pointer

or the Clang equivalents in test builds. These tools catch real examples of null pointer dereference the moment your tests hit them, instead of waiting for a user to report a crash.

Organizations that publish secure coding guidelines, such as the CERT Coordination Center at cmu.edu, explicitly recommend this kind of tooling for memory safety.


FAQ: short answers about null pointer segmentation faults

What are common real examples of segmentation fault examples: null pointer dereference?

Common real examples include dereferencing a null pointer returned by malloc or fopen, calling a virtual method on a null C++ object, using an empty smart pointer as if it were valid, dereferencing null at an FFI boundary in Rust or Go, and reading from a global pointer that another thread has freed and set to null.

Can a null pointer dereference ever be safe?

In normal user-space programs on modern operating systems, no. Accessing address 0 is blocked by the OS and will trigger a segmentation fault. Some kernel or bare-metal environments historically used address 0 for special purposes, but that’s not something you should rely on in application code.

How do I debug an example of null pointer dereference?

Run the program under a debugger like gdb or lldb, reproduce the crash, and inspect the backtrace. Look for the line where a pointer is dereferenced and check its value. If it’s 0x0, you have a null pointer dereference. Then trace back where that pointer came from and add checks or fix lifetime issues. Sanitizers like AddressSanitizer and tools documented by LLVM at llvm.org are very effective here.

Are all segmentation faults caused by null pointer dereference?

Not at all. Segmentation faults also come from buffer overflows, stack smashing, use-after-free, and writing to read-only memory. Null pointer dereference is just one of the best examples for teaching and understanding the broader category of memory safety bugs.

Why are null pointer dereferences still common in 2024–2025?

Because a huge amount of infrastructure is still written in C and C++, and new systems code is continuously added around it. While memory-safe languages are gaining ground, the combination of legacy code, performance constraints, and FFI layers means examples of segmentation fault examples: null pointer dereference are still very much alive in modern logs and crash reports.

Explore More Segmentation Faults

Discover more examples and insights in this category.

View All Segmentation Faults