0
0
CDebug / FixBeginner · 4 min read

How to Handle Segmentation Fault in C: Causes and Fixes

A segmentation fault in C happens when your program tries to access memory it shouldn't, like a bad pointer or out-of-bounds array. To handle it, fix the code causing invalid memory access by checking pointers and array limits, and use debugging tools like gdb to find the exact cause.
🔍

Why This Happens

A segmentation fault occurs when your program tries to read or write memory that it is not allowed to access. This often happens because of using a pointer that is not initialized, accessing an array outside its bounds, or dereferencing a NULL pointer.

c
#include <stdio.h>

int main() {
    int *ptr = NULL;
    // Trying to write to NULL pointer causes segmentation fault
    *ptr = 10;
    printf("Value: %d\n", *ptr);
    return 0;
}
Output
Segmentation fault (core dumped)
🔧

The Fix

To fix a segmentation fault, ensure pointers are properly initialized before use. Avoid dereferencing NULL pointers and check array bounds. Here, we allocate memory before using the pointer.

c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = malloc(sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    *ptr = 10;
    printf("Value: %d\n", *ptr);
    free(ptr);
    return 0;
}
Output
Value: 10
🛡️

Prevention

To avoid segmentation faults in the future, always initialize pointers before use, check array indexes carefully, and free allocated memory properly. Use tools like valgrind to detect memory errors and gdb to debug crashes. Writing defensive code with checks for NULL pointers and valid ranges helps prevent invalid memory access.

⚠️

Related Errors

Other common memory errors include:

  • Buffer overflow: Writing past the end of an array.
  • Use-after-free: Accessing memory after it has been freed.
  • Double free: Freeing the same memory twice.

These can also cause crashes and should be fixed by careful memory management and using debugging tools.

Key Takeaways

Segmentation faults happen when accessing invalid memory like NULL or out-of-bounds pointers.
Always initialize pointers and check array bounds before accessing memory.
Use debugging tools like gdb and valgrind to find and fix memory errors.
Free allocated memory properly and avoid using pointers after freeing.
Write defensive code with checks to prevent invalid memory access.