What is a segmentation fault in C?

A segmentation fault (segfault) happens when a program reads or writes memory that it should not touch. The operating system stops the program.

Common causes:

  • Dereferencing a NULL or uninitialized pointer.
  • Accessing an array outside its limits.
  • Using memory after free().
  • Very deep recursion (stack overflow).
  • Writing to a string literal, like char *s = "abc"; s[0] = 'x';.

To find it, compile with -g and run with a debugger like GDB, or use -fsanitize=address to see the exact line.


Learn more about the similar topics:
Tutorials
C Pointers
C Pointer Arithmetic
C Pointer to Pointer
C Pointers and Arrays
C Pointers and Functions
C Dynamic Memory Allocation
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is a pointer in C?
What is a NULL pointer in C?
What is the difference between malloc() and calloc() in C?
What is a memory leak in C and how to avoid it?
What is a dangling pointer in C?
What is the difference between an array and a pointer in C?
What is a void pointer in C?