C Compiler Logo

Segmentation Fault

Segmentation Fault

runtime

Segmentation fault (core dumped)

Description

The program tried to access memory it doesn't have permission to access.

Common Causes

Example of Error

Error Code

int main() {
    int *ptr = NULL;
    *ptr = 10;  // Dereferencing NULL pointer
    return 0;
}

Solution

Check pointers before dereferencing them and ensure array accesses are within bounds.

Corrected Code

#include <stdlib.h>

int main() {
    int *ptr = malloc(sizeof(int));
    if (ptr != NULL) {
        *ptr = 10;
        free(ptr);
    }
    return 0;
}

Additional Tips