πŸ”§ Error Fixes
Β· 1 min read

Segmentation Fault β€” What It Means and How to Fix It


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