🔍
Artificial Intelligence Cybersecurity Windows Mac Android iPhone Software How-To Guides Reviews Comparisons Productivity Internet Apps Cloud Business Software About Contact

Segmentation Fault in C/C++: Causes and How to Debug

A segmentation fault (segfault) occurs when a program tries to access memory it is not allowed to access. It is one of the most common and frustrating errors in C and C++ programming.

What Causes Segmentation Faults?

Common causes: dereferencing a null pointer, accessing freed memory (dangling pointer), buffer overflow (writing past array bounds), stack overflow (infinite recursion), or using uninitialized pointers. The OS sends SIGSEGV and terminates the program.

How to Debug with GDB

Compile with debugging symbols: gcc -g program.c -o program. Run in GDB: gdb ./program. Use run to start the program. When the segfault occurs, use backtrace (bt) to see the call stack. Use print variable to inspect values. Use list to see the source code around the crash.

Using Valgrind to Detect Memory Errors

Valgrind detects memory errors without modifying your code. Run: valgrind ./program. It reports invalid reads/writes, use-after-free, memory leaks, and uninitialized values. Fix each error Valgrind reports until the program runs cleanly.

How to Prevent Segfaults

Always initialize pointers to NULL or valid memory. Check pointer validity before dereferencing: if (ptr != NULL). Use bounds checking with functions like strncpy instead of strcpy. Free memory exactly once. Use smart pointers in C++. Enable compiler warnings with -Wall -Wextra.

Using AddressSanitizer

Modern compilers include AddressSanitizer (ASan). Compile with: gcc -fsanitize=address -g program.c. ASan detects buffer overflows, use-after-free, and memory leaks with detailed reports including the exact line of the error.