Segmentation Fault in C: Causes and Fixes

Find and fix segmentation faults in C. Trace an out-of-bounds read, run AddressSanitizer, and compare complete broken and fixed C examples.

Start with a working diagnosis

Find an out-of-bounds read and fix it

A segmentation fault is an operating-system error that can occur when a program accesses memory it is not allowed to use. Check null pointers, array bounds, and freed memory. Invalid C memory accesses are undefined behavior: they do not always produce a segmentation fault.

1. What happens on the next iteration?

int values[3] = {10, 20, 30};
int total = 0;
for (int i = 0; i <= 3; ++i) {
    total += values[i];
}

There are three elements. The valid indices are 0, 1, and 2.

Loop condition: i <= 3

values[0]10
values[1]20
values[2]30
values[3]invalid

This is an explanatory model of array access. Test the real C program below to see a diagnostic.

2. Find the error in a real C program

Use Clang with AddressSanitizer on Linux, macOS, or WSL with the compiler installed. Run these commands in the folder containing the downloaded files.

Download broken exampleDownload fixed example
Show the complete broken program
/* Intentionally incorrect: run with AddressSanitizer for the lesson. */
#include <stdio.h>

int main(void) {
    int values[3] = {10, 20, 30};
    int total = 0;
    for (int i = 0; i <= 3; ++i) {
        total += values[i]; /* i == 3 is outside the array. */
    }
    printf("total = %d\n", total);
    return 0;
}
clang -std=c11 -Wall -Wextra -g -O0 -fsanitize=address -fno-omit-frame-pointer bounds-bug.c -o bounds-bug
./bounds-bug

Typical report excerpt; addresses and formatting vary by platform. “stack-buffer-overflow” identifies an out-of-bounds stack access, and “READ” tells you the program was reading memory.

ERROR: AddressSanitizer: stack-buffer-overflow ...
READ of size 4 ...
... main ... bounds-bug.c:8 ...

The invalid read happens at total += values[i]. The cause is the loop condition i <= 3, which lets the loop reach i = 3.

3. Fix the bound and run again

Derive the element count with sizeof and loop only while i < count.

Show the complete fixed program
#include <stdio.h>

int main(void) {
    int values[3] = {10, 20, 30};
    int total = 0;
    const size_t count = sizeof values / sizeof values[0];
    for (size_t i = 0; i < count; ++i) {
        total += values[i];
    }
    printf("total = %d\n", total);
    return 0;
}
clang -std=c11 -Wall -Wextra -g -O0 -fsanitize=address bounds-fixed.c -o bounds-fixed
./bounds-fixed
total = 60

The fixed example no longer reads past this array. A clean run is not proof that every possible bug in a larger program has been removed.

Continue learning: pointer visualization · malloc / free · GDB · AddressSanitizer documentation

Updated: 2026-10-01

📖 What you'll learn on this page
✅ Must-know essentials
  • A segmentation fault means accessing forbidden memory
  • NULL dereference, out-of-bounds access, and use-before-init are the top causes
  • Division by zero and stack overflow
⭐ Read if you have time
  • The dangers of undefined behavior
  • Detection with valgrind and sanitizers
  • Core dumps and post-mortem debugging with gdb

What are Runtime Errors — It Compiled, but...

A successful compile just means the syntax is correct. A runtime error is when the program crashes while running. Compiler warnings can identify some causes, but a successful build does not guarantee safe execution.
Segmentation Fault
Reading or writing forbidden memory. A common memory-access error.
Bus Error
Memory alignment violations. Whether they occur depends on the platform.
Floating Point Exception
Often caused by integer division by zero (x / 0). Strictly, it is undefined behavior: on some platforms such as Apple Silicon (ARM) the program doesn't stop and just continues with a garbage value.
Infinite loop / freeze
The program never terminates. Kill it with Ctrl+C.
General approach: (1) use printf to find out how far execution gets, (2) print the values of suspicious variables, and (3) carefully check array indices and pointers.

Segmentation Fault — Common Causes

Segmentation fault (core dumped) is a common error when learning pointers and arrays. It means "you touched memory you weren't allowed to."

Five common causes

1
Out-of-bounds array access
int a[5];
a[10] = 99;  // only a[0]..a[4] exist; writing a[10] is undefined behavior (may crash)

// Common mistake: wrong loop bound
for (int i = 0; i <= 5; i++)  // accesses a[5] when i=5 -> NG
  a[i] = i;
2
Dereferencing a NULL pointer
int *p = NULL;
*p = 10;  // writing to the address NULL points to -> Segfault

// Fix: NULL-check before use
if (p != NULL) { *p = 10; }
3
Missing & in scanf
int x;
scanf("%d", x);   // NG: uses the "value" of x as an address -> crash
scanf("%d", &x);  // OK: passes the "address" of x
4
Using an uninitialized pointer
int *p;     // uninitialized -> contains garbage address
*p = 42;    // writing to a garbage address -> Segfault

// Fix: always initialize, or allocate with malloc before use
5
Stack overflow (infinite recursion)
int fact(int n) {
  return n * fact(n - 1); // no base case -> recurses forever -> stack overflow
}
// Fix: add if (n <= 1) return 1;

Memory-Related Errors — Hidden Landmines

Memory bugs can surface as wrong results without ever triggering a segfault.
Buffer overrun
Writing past the end of an array corrupts neighboring memory.
char name[5];
strcpy(name, "HelloWorld"); // only 5 bytes but 10+NUL -> overflow

// Fix: snprintf(name, sizeof name, "%s", "Hello"); /* truncated, NUL-terminated */
Memory leak
Forgetting to free memory allocated by malloc leaves unreachable memory that accumulates over time.
int *p = malloc(sizeof(int) * 100);
// ... use p ...
// forgot free(p); -> memory leak
Dangling pointer / double free
Using a pointer after it's been freed leads to unpredictable behavior.
free(p);
*p = 10;   // writing to freed memory -> undefined behavior
free(p);   // double free -> possible crash

// Fix: set p = NULL; after free

Logic Errors — It Runs But the Answer is Wrong

No crash, but the result is wrong. These are the hardest bugs to track down — printf debugging is your best friend.
Integer division pitfall
int a = 7, b = 2;
double avg = a / b;     // -> 3.000000 (not 3.5!)
double avg = (double)a / b; // -> 3.500000 (OK)
Integer divided by integer truncates the fractional part. Cast one side to double.
Operator precedence
if (x & 1 == 0)   // parsed as x & (1==0) - not what you meant!
if ((x & 1) == 0) // OK: explicit parens
Bitwise vs. comparison precedence is counter-intuitive. When in doubt, add parentheses.
Missing break in switch (fall-through)
switch (n) {
  case 1: printf("one\n");  // no break -> case 2 and case 3 also run
  case 2: printf("two\n");
  case 3: printf("three\n");
}
Stray semicolon after if
if (x > 0);  // ← this ; ends the if statement
{
  printf("positive\n"); // ← always runs!
}

Troubleshooting Checklist

When you hit an error, walk through this checklist from top to bottom.

If you see a Segmentation Fault

When results are wrong

When you have lots of compile errors

← Previous lesson
Lesson 47: Compile Errors

Related lessons

Reference
Lesson 47: Compile Errors Dictionary
A catalog of C compile errors and how to fix them.
Loops, Arrays, Strings
Lesson 19: Debugging Techniques
How to debug C programs.
Advanced
Lesson 36: Pointer Basics
Understand C pointers with memory visualization.

FAQ

Q. What is the difference between compile errors and runtime errors?

A. Compile errors are syntax problems caught during compilation; no executable is produced. Runtime errors occur while the program is running — the code compiles but the program crashes. Runtime errors are harder to detect.

Q. I got a segmentation fault. What causes it?

A. Segmentation faults come from illegal memory access. The main culprits: (1) dereferencing a NULL pointer, (2) accessing freed memory, (3) out-of-bounds array access, and (4) stack overflow. Review your pointer and memory handling.

Q. How do I debug an infinite loop?

A. (1) Check the loop condition and exit criterion. (2) Use printf() on loop variables to see where they diverge from your expectations. (3) A step debugger is also effective. Most infinite loops come from bad loop conditions or a missing increment.

Q. How do I find memory corruption?

A. Memory corruption is tricky because the symptoms often appear far from the actual cause. Effective tools include (1) valgrind (check platform support; commonly used on Linux), (2) sanitizers like UBSan and ASan, and (3) careful review of your array and pointer usage.

Review Quiz

Check your understanding.

Q1. What is the main cause of segmentation faults?

Syntax errors
Illegal memory access
Wrong variable names

Common causes include NULL pointer dereferences, out-of-bounds array access, and using freed memory. Compiler warnings and sanitizers can help detect some of these mistakes.

Q2. What happens when you divide by 0?

Compile error
Undefined behavior (on many systems it stops with a runtime error)
The result is always 0 on every system

Integer division by 0 is undefined behavior. On Intel PCs and similar it stops with "Floating point exception", but on Apple Silicon (ARM) it doesn't trap — a value such as 0 is returned and the program keeps running. Either way the result is wrong, so if you're dividing by a variable, check that it's not zero first.

Q3. How do you fix an infinite loop?

Change the compiler settings
Revisit the loop's exit condition
Change the variable type

Infinite loops happen when the exit condition is never met. Check for a missing counter update or flawed condition logic.

Share this article
Share on X Share on Facebook