Linux Tips guides, explanations and reader checklists on whilenetworking.com

Debugging ‘Segmentation Fault’ Errors in C/C++ Programs Running on Linux

A segmentation fault (segfault) occurs when a program attempts to access a memory location that it is not permitted to touch, such as dereferencing a null…

A segmentation fault (segfault) occurs when a program attempts to access a memory location that it is not permitted to touch, such as dereferencing a null pointer, accessing freed memory, or overflowing a buffer. For IT students and junior engineers working with C and C++ on Linux, this is one of the most common yet frustrating runtime errors. The immediate reaction is often panic, but these crashes are almost always symptomatic of logical errors in code rather than hardware failures. Understanding how to isolate the cause using standard Linux tools is a fundamental skill for any systems programmer.

This guide walks you through a realistic lab scenario where a simple C program crashes unexpectedly. We will use concrete shell commands, analyze core dumps, and apply practical fixes. Remember that while these steps are generally applicable, specific behaviors can vary based on compiler versions (GCC, Clang), kernel configurations, and hardware architecture. Always test debugging procedures in a safe, isolated environment before applying them to production systems.

Understanding the Crash Signal

When a segmentation fault occurs, the operating system sends a SIGSEGV signal to the offending process. By default, this signal terminates the program. However, modern Linux distributions often generate a “core dump”—a snapshot of the program’s memory at the moment of the crash—allowing developers to inspect the state of variables and stack frames post-mortem.

To enable core dumps on most systems, you must ensure the core_pattern setting allows file generation and that your user has write permissions in the current directory. You can check the current pattern by running:

cat /proc/sys/kernel/core_pattern

If the output is just |/syslog, core dumps are being sent to the system log rather than saved as files. To save them as files named after the executable (e.g., my_program.core), you can set the pattern explicitly:

echo "core.%e" | sudo tee /proc/sys/kernel/core_pattern

Note: Some systems require root privileges to change this setting. If your user lacks permissions, you may need to adjust the ulimit settings or run the program as root (not recommended for security).

Step 1: Reproduce and Locate the Crash

The first step in debugging is consistently reproducing the error. In a workplace scenario, this might involve running a nightly build script that occasionally fails. For students, it means compiling and executing test cases until the crash happens reliably.

Consider a hypothetical C program named memory_leak.c that attempts to access an array out of bounds:

#include <stdio.h>

int main() {
    int arr[5];
    // Attempting to access index 10, which is out of bounds
    printf("%d\n", arr[10]); 
    return 0;
}

Compile this with GCC, ensuring debug symbols are included. Debug symbols (-g) are crucial because they allow the debugger to map memory addresses back to source code lines:

gcc -g -o memory_leak memory_leak.c

Now, run the program. You will likely see a message like AddressSanitizer: ... if compiled with sanitizers, or a standard Segmentation fault (core dumped) from the kernel. If no core file appears immediately, check your ulimit:

ulimit -c unlimited

Run the program again. Look for a new .core file in your working directory. If you do not see one, verify that the current user has write access to the folder.

Step 2: Analyzing with GDB and Core Dumps

Once a core dump is generated, you can use the GNU Debugger (gdb) to inspect where the crash occurred. Install gdb if it is not present:

sudo apt-get install gdb   # Debian/Ubuntu
sudo yum install gdb       # RHEL/CentOS

Launch GDB with both the executable and the core file:

gdb ./memory_leak ./memory_leak.core

Inside the GDB prompt, type bt (backtrace) to see the call stack. This command prints the sequence of function calls leading up to the crash.

(gdb) bt
#0  0x00005555555550f2 in main () at memory_leak.c:6
#1  0x00007ffff... in ?? ()

The output indicates the crash happened at line 6 of memory_leak.c, which matches our code where we accessed arr[10]. You can also use info registers to inspect register values or x/20wx $rsp to view memory around the stack pointer. This level of detail helps distinguish between a buffer overflow, a null pointer dereference, and other memory violations.

Step 3: Using Compiler Sanitizers for Automated Detection

While GDB is powerful, compiling with AddressSanitizer (ASan) provides immediate feedback without needing core dumps. ASan instruments the binary to detect out-of-bounds accesses, use-after-free errors, and memory leaks at runtime.

Recompile your program with sanitizers enabled:

gcc -g -fsanitize=address -o memory_leak_sanitized memory_leak.c

Run the sanitized executable:

./memory_leak_sanitized

Expected output will look like this:

=================================================================
==7845==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000001a0
...
#0 0x5555555550f2 in main (/home/user/memory_leak_sanitized+0x28)

The sanitizer highlights the exact offset and line number where the violation occurred. This approach is highly recommended for students learning C/C++ as it automates much of the detective work required with raw core dumps.

Common Mistakes and Fixes

A frequent mistake among beginners is ignoring compiler warnings. Warnings about signed integer overflow or unused variables can often precede segmentation faults. Always compile with -Wall -Wextra flags to catch these early:

gcc -g -Wall -Wextra -o memory_leak memory_leak.c

Another common error is running the program without sufficient stack size limits on systems with restrictive ulimit settings. Additionally, forgetting to enable core dumps (ulimit -c unlimited) can lead to confusion when a crash occurs but no diagnostic file is created. Always verify your environment setup before assuming the code is broken; sometimes the issue is purely environmental.

Student Practice Task

To reinforce these skills, try modifying the memory_leak.c example to intentionally cause a “use-after-free” error (freeing memory and then accessing it). Compile with AddressSanitizer and observe how the tool reports the specific sequence of events. This exercise builds intuition for managing dynamic memory allocation, a critical aspect of C/C++ programming on Linux.

Industry Application Checklist

In a professional setting, segmentation faults can take down services or expose security vulnerabilities. Before deploying a binary to production:
1. Compile with debug symbols and sanitizers in your CI/CD pipeline.
2. Ensure core dumps are configured to write to a secure, monitored location.
3. Review backtraces from any crash logs to identify root causes before patching.

By mastering these debugging techniques, you transform segmentation faults from mysterious roadblocks into solvable puzzles, accelerating your growth as a Linux systems engineer.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.