Segmentation fault (core dumped)
Your program tried to access memory it doesnβt own. The OS killed it to prevent damage. This is almost always a pointer or array issue.
Fix 1: Null Pointer Dereference
// β Pointer is NULL
int *ptr = NULL;
*ptr = 42; // π₯ Segfault
// β
Check before dereferencing
if (ptr != NULL) {
*ptr = 42;
}
Fix 2: Array Out of Bounds
// β Accessing beyond array size
int arr[5];
arr[10] = 42; // π₯ Segfault
// β
Stay within bounds
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
Fix 3: Using Freed Memory
// β Use after free
int *ptr = malloc(sizeof(int));
free(ptr);
*ptr = 42; // π₯ Segfault
// β
Set to NULL after free
free(ptr);
ptr = NULL;
Fix 4: Stack Overflow from Deep Recursion
// β No base case
void recurse() {
recurse(); // π₯ Eventually segfaults
}
// β
Add a base case
void recurse(int n) {
if (n <= 0) return;
recurse(n - 1);
}
Fix 5: Writing to Read-Only Memory
// β String literals are read-only
char *str = "hello";
str[0] = 'H'; // π₯ Segfault
// β
Use a char array
char str[] = "hello";
str[0] = 'H'; // Works
Debugging
# Compile with debug symbols
gcc -g -o myapp myapp.c
# Run with Valgrind (finds memory errors)
valgrind ./myapp
# Run with AddressSanitizer
gcc -fsanitize=address -g -o myapp myapp.c
./myapp
# Get a backtrace from core dump
gdb ./myapp core
(gdb) bt