Segmentation fault (core dumped)
Segmentation fault (core dumped)
DodaTech
3 min read
Segmentation fault (core dumped) means your program tried to access memory it does not have permission to access. The OS memory protection unit killed the process.
What It Means
The CPU triggered a segmentation fault when your program attempted to read from or write to an invalid memory address. The “core dumped” part means the OS saved a core dump file for debugging.
Why It Happens
- Dereferencing a
NULLor uninitialized pointer - Writing past the end of an array (buffer overflow)
- Using a dangling pointer that points to freed memory
- Recursive function calls causing stack overflow
- Modifying a string literal (which is read-only)
How to Fix It
Step 1: Check for NULL pointer dereference
// bad.cpp
int* ptr = nullptr;
*ptr = 42; // segmentation fault!
// fixed.cpp
int* ptr = nullptr;
if (ptr != nullptr) {
*ptr = 42;
} else {
ptr = new int(42);
}Step 2: Avoid buffer overflows
// bad.cpp
int arr[5];
for (int i = 0; i <= 5; ++i) { // off-by-one: writes past the end
arr[i] = i * 10;
}// fixed.cpp
int arr[5];
for (int i = 0; i < 5; ++i) {
arr[i] = i * 10;
}Step 3: Fix dangling pointers
// bad.cpp
int* ptr = new int(42);
delete ptr;
*ptr = 100; // dangling pointer — undefined behavior
// fixed.cpp
int* ptr = new int(42);
delete ptr;
ptr = nullptr; // good practice
// Do not use ptr again without reassigning
Step 4: Debug with GDB
# Compile with debug symbols
g++ -g crash.cpp -o crash
# Run with GDB
gdb ./crash
(gdb) run
(gdb) bt # backtrace — shows the call stack
(gdb) info locals # show local variable values
(gdb) list # show source code around the crashStep 5: Detect memory errors with Valgrind
g++ -g crash.cpp -o crash
valgrind --leak-check=full ./crashValgrind reports invalid reads/writes, use-after-free, and memory leaks with exact line numbers.
Step 6: Use address sanitizer
g++ -g -fsanitize=address crash.cpp -o crash
./crashThe address sanitizer catches buffer overflows, use-after-free, and memory leaks at runtime with detailed diagnostics.
Previous
PHP Fatal error: Cannot redeclare ...
Next
SSL: hostname mismatch (the certificate does not match the server name)
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro