Accessing memory that your program is not allowed to access.
A segmentation fault (segfault) occurs when a program tries to access a memory location that it doesn't have permission to access. The operating system detects the illegal memory access and terminates the program with signal SIGSEGV. This is one of the most common and frustrating bugs in C/C++.
Common causes: dereferencing a null or uninitialized pointer, accessing an array beyond its bounds, dereferencing a dangling pointer (pointing to freed memory), stack overflow from deep recursion, or writing to read-only memory segments.
1#include <iostream>2 3int main() {4 int* ptr = nullptr; // Null pointer5 6 // Dereferencing a null pointer — segfault!7 *ptr = 42;8 std::cout << *ptr << std::endl;9 10 return 0;11}1#include <iostream>2 3int main() {4 // Fix 1: Initialize pointer with a valid address5 int value = 42;6 int* ptr = &value;7 *ptr = 100;8 std::cout << *ptr << std::endl; // 1009 10 // Fix 2: Dynamically allocate memory before use11 int* heapPtr = new int(42);12 std::cout << *heapPtr << std::endl; // 4213 delete heapPtr; // Always free heap memory14 heapPtr = nullptr; // Prevent dangling pointer15 16 // Fix 3: Check for null before dereferencing17 int* maybeNull = nullptr;18 if (maybeNull != nullptr) {19 std::cout << *maybeNull << std::endl;20 } else {21 std::cout << "Pointer is null, skipping." << std::endl;22 }23 24 return 0;25}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
`ptr` is initialized to `nullptr`, which is address `0x0`. Attempting to write to `*ptr` (dereferencing null) causes the OS to detect unauthorized memory access. The OS sends SIGSEGV to the process, immediately terminating it with a "Segmentation fault (core dumped)" message.