How to Fix Linux Segmentation Fault (core dumped) Error
In this tutorial, you'll learn about How to Fix Linux Segmentation Fault (core dumped) Error. We cover key concepts, practical examples, and best practices.
You run a program and get Segmentation fault (core dumped) — the program tried to access memory it does not have permission to access, often due to a bug, corrupted binary, or hardware issue.
The Problem
./myapp
Segmentation fault (core dumped)
Step-by-Step Fix
Step 1: Enable core dumps
ulimit -c unlimited
Make permanent in ~/.bashrc:
echo 'ulimit -c unlimited' >> ~/.bashrc
Step 2: Reproduce the crash
./myapp
Check for the core file:
ls -la core* /var/lib/systemd/coredump/
Step 3: Analyze with gdb
gdb ./myapp core
Inside gdb, get a backtrace:
(gdb) bt
(gdb) bt full
This shows the exact function call chain that led to the crash.
Step 4: Check for common causes
Buffer overflow:
char buf[10];
strcpy(buf, "this string is way too long"); // WRONG
strncpy(buf, "short", sizeof(buf) - 1); // RIGHT
Null pointer dereference:
int *p = NULL;
*p = 42; // WRONG
Use-after-free:
free(ptr);
ptr[0] = 0; // WRONG
Step 5: Reinstall the affected package
sudo apt reinstall <package>
Step 6: Check for hardware issues
Run memory test:
sudo apt install memtester
memtester 1024 1
Check system logs:
dmesg | grep -i "segfault\|error"
Expected:
[12345.678] myapp[1234]: segfault at 7f1234 ip 00007f5678 sp 00007f9012 error 6
Step 7: Update system and libraries
sudo apt update && sudo apt upgrade
Prevention Tips
- Enable core dumps in development environments
- Use AddressSanitizer during development:
gcc -fsanitize=address -g - Always check pointer validity before dereferencing
- Use
valgrindto detect memory errors - Keep software updated to get bug fixes
Common Mistakes with segfault
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world LINUX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro