Course contentsShow
← Rust
Lesson 1409 of 1,91012. Unsafe Rust and Low-Level AccessFree lesson

Debugging Segmentation Faults

You will use low-level tooling to isolate the precise source of memory corruption in unsafe blocks.

In this lesson, you will learn how to use low-level tooling to pinpoint the exact instruction causing a segmentation fault when your unsafe code violates memory safety.

When an unsafe block triggers a segmentation fault, Rust’s runtime doesn't offer a stack trace because the CPU has literally been asked to access an invalid address. To recover the context, we must look at the processor state at the moment of the crash.

Using GDB or LLDB

When a program crashes with a segmentation fault, the operating system raises a SIGSEGV. To debug this, run your binary through a debugger like gdb or lldb.

gdb ./my_unsafe_program
(gdb) run
# ... program crashes ...
(gdb) backtrace

The backtrace (or bt) command will show you the exact function and line number where the CPU encountered the invalid memory access. If the crash occurs inside an unsafe block, the debugger often shows the assembly instruction that failed.

Isolating the Pointer

If the backtrace points to a raw pointer dereference, you need to verify if the pointer is null, unaligned, or pointing to freed memory. You can inspect the pointer value before the crash using print statements or, better yet, conditional breakpoints in the debugger:

# Set a breakpoint on the unsafe block
(gdb) break src/main.rs:42
(gdb) run
# Check the pointer value before it is dereferenced
(gdb) print my_ptr

The "Address Sanitizer" Strategy

For more complex memory corruption, such as writing past the end of a buffer, standard debugging is often too slow. Use the Address Sanitizer (ASan), which instruments your code to track every memory access. By compiling with -Zsanitizer=address, the compiler injects checks that stop the program exactly when an out-of-bounds access occurs, rather than waiting for the CPU to trigger a segmentation fault later. This is the most efficient way to catch "use-after-free" or "buffer overflow" bugs hidden in unsafe blocks.

Key Takeaway: When a segmentation fault occurs in unsafe Rust, use a debugger’s backtrace to find the instruction and ASan to detect the precise moment the memory contract was broken.