Segmentation Fault in C

A segmentation fault in C is one of the most common runtime errors in low-level programming. It usually happens when a program tries to access memory that it is not allowed to access. The compiler often cannot detect this problem because the code may look syntactically correct. The crash happens only when the program runs and touches invalid memory.

This topic is important because segmentation faults are closely connected to pointers, arrays, dynamic memory allocation, and function calls. If you understand why they happen, you can write safer C code and debug crashes much faster. In this article, we will understand what a segmentation fault in C means, its causes, examples, debugging methods, and how to avoid it.

What is a Segmentation Fault in C?

A segmentation fault in C is a runtime error that occurs when a program accesses an invalid memory location.

A segmentation fault usually means the program tried to read from or write to memory that does not belong to it in a valid way.

Operating systems protect memory regions. When a program violates those rules, the operating system stops it and reports a segmentation fault.

Why Segmentation Fault Happens in C

C gives direct access to memory through pointers. That is powerful, but it also makes it possible to access memory incorrectly.

  • using an uninitialized pointer
  • dereferencing a NULL pointer
  • accessing memory after free
  • going outside array bounds
  • writing to read-only memory
  • causing stack overflow through deep recursion

These issues are common because C does not perform automatic bounds checking or automatic memory safety checks.

Common Causes of Segmentation Fault in C

Dereferencing a NULL Pointer

A NULL pointer does not point to a valid object. Trying to access memory through it can crash the program.

#include <stdio.h>

int main(void) {
    int *ptr = NULL;
    printf("%d\n", *ptr);
    return 0;
}

Using an Uninitialized Pointer

If a pointer is declared but not assigned a valid address, dereferencing it is unsafe because it contains an unknown value.

#include <stdio.h>

int main(void) {
    int *ptr;
    *ptr = 10;
    return 0;
}

Accessing Array Out of Bounds

Reading or writing outside the valid range of an array can overwrite unrelated memory or crash the program.

#include <stdio.h>

int main(void) {
    int arr[3] = {1, 2, 3};
    arr[10] = 50;
    return 0;
}

Using Memory After free

After memory is released, the pointer becomes invalid for normal use. Accessing it again creates undefined behavior and may produce a segmentation fault.

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

int main(void) {
    int *ptr = malloc(sizeof(int));
    if (ptr == NULL) {
        return 1;
    }

    *ptr = 25;
    free(ptr);
    printf("%d\n", *ptr);
    return 0;
}

Writing to a String Literal

String literals are usually stored in read-only memory. Modifying them is unsafe.

#include <stdio.h>

int main(void) {
    char *str = "hello";
    str[0] = 'H';
    return 0;
}

Stack Overflow from Deep Recursion

If function calls keep adding stack frames without stopping, the stack can overflow and the program may crash.

void recurse(void) {
    recurse();
}

int main(void) {
    recurse();
    return 0;
}

Segmentation Fault Example in C

The following small example shows a classic invalid memory access using a NULL pointer.

#include <stdio.h>

int main(void) {
    int *p = NULL;
    *p = 100;
    return 0;
}

Here p does not point to a valid integer object. Writing through it attempts to store data in an invalid location, and the operating system can terminate the program with a segmentation fault.

How to Debug Segmentation Fault in C

Segmentation faults are easier to fix when you use a systematic debugging process.

  • check recent pointer and array changes first
  • look for NULL pointers and uninitialized pointers
  • verify array indexes and loop limits
  • check whether freed memory is being reused
  • confirm recursive functions have a stopping condition
  • use debugging tools instead of guessing

On Linux, a common workflow is compiling with debug information and then using gdb.

gcc -g program.c -o program
./program
gdb ./program

Compiler warnings also help. Strong warning flags can catch bad patterns before runtime.

gcc -Wall -Wextra -g program.c -o program

How to Prevent Segmentation Fault in C

  • initialize pointers before using them
  • check for NULL before dereferencing when needed
  • do not access arrays outside valid bounds
  • free memory only once
  • set pointers to NULL after free when practical
  • avoid writing to string literals
  • keep recursion under control
  • use sizeof carefully in allocations

Careful pointer handling is the best long-term defense against segmentation faults.

Segmentation Fault vs Other Runtime Errors in C

Error TypeMeaningTypical Cause
Segmentation faultInvalid memory accessBad pointer, out-of-bounds access, freed memory use
Memory leakAllocated memory not releasedMissing free
Dangling pointer issuePointer refers to released memoryUsing pointer after free
Divide by zeroInvalid arithmetic operationDivision with zero denominator

Best Practices for Avoiding Segmentation Fault in C

  • write small testable functions so bugs are easier to isolate
  • validate all pointer-returning functions
  • use clear ownership rules for dynamically allocated memory
  • prefer array length variables instead of magic numbers
  • review loop limits carefully
  • compile with warnings enabled
  • debug crashes with tools instead of trial and error

FAQs

What causes segmentation fault in C?

A segmentation fault in C is usually caused by invalid memory access such as dereferencing a NULL pointer, using an uninitialized pointer, going outside array bounds, or using memory after free.

Can array out of bounds cause segmentation fault in C?

Yes. Accessing an array outside its valid range can overwrite or read invalid memory and may produce a segmentation fault.

Does every invalid pointer use cause segmentation fault?

No. Invalid pointer use leads to undefined behavior. Sometimes the program crashes immediately, sometimes later, and sometimes it appears to work while still being wrong.

How do I fix segmentation fault in C?

Find the invalid memory access, then correct the pointer logic, array bounds, allocation handling, or recursion depth. Debuggers and compiler warnings make this much easier.