How do I diagnose and fix 'segmentation fault (core dumped)' in C++?

Segmentation faults are a common error in C++ that occur when your program tries to access a memory location that it's not allowed to. This can happen for a variety of reasons, such as dereferencing a null pointer, accessing memory out of bounds, or using uninitialized pointers.

To diagnose and fix segmentation faults, consider the following steps:

  1. Check for Null Pointers: Ensure that pointers are initialized before use.
  2. Use Debugging Tools: Utilize tools like gdb (GNU Debugger) to trace where the segmentation fault occurs.
  3. Check Array Bounds: Make sure that any array accesses are within valid bounds.
  4. Review Dynamic Memory Usage: Ensure that memory allocated with new is properly deallocated with delete.
  5. Use Smart Pointers: Consider using smart pointers (like std::unique_ptr or std::shared_ptr) to manage lifetimes and ownership of resources automatically.

Here's a simple example demonstrating a common cause of segmentation faults:


#include <iostream>

int main() {
    int* ptr = nullptr; // Initialize pointer to null
    *ptr = 42; // Attempt to dereference the null pointer
    std::cout << *ptr << std::endl; // This line will cause a segmentation fault
    return 0;
}

segmentation fault C++ debugging memory management null pointer gdb dynamic memory array bounds