What is Segmentation Fault in C: Explanation and Example
segmentation fault in C is an error that occurs when a program tries to access memory it is not allowed to use. It usually happens when you use invalid pointers or go beyond the limits of an array.How It Works
Imagine your computer's memory as a big apartment building where each apartment is a small block of memory. Your program is only allowed to enter certain apartments it owns. A segmentation fault happens when your program tries to enter an apartment it doesn't have permission for.
In C, this often occurs when you use a pointer that points to a wrong or uninitialized memory location, or when you try to access an array outside its valid range. The operating system protects these memory areas to prevent programs from accidentally changing or reading data they shouldn't.
When this protection is triggered, the operating system stops your program immediately and reports a segmentation fault, which helps you find bugs related to incorrect memory use.
Example
This example shows a segmentation fault caused by accessing an array out of its bounds.
#include <stdio.h> int main() { int numbers[3] = {1, 2, 3}; // Accessing index 5 which is outside the array size printf("Number: %d\n", numbers[5]); return 0; }
When to Use
You don't want to cause segmentation faults, but understanding them helps you write safer C programs. Use this knowledge when working with pointers, arrays, or dynamic memory to avoid accessing invalid memory.
In real-world programming, segmentation faults often appear during debugging when you accidentally dereference null or wild pointers, or when you forget to allocate memory before use. Catching these errors early prevents crashes and data corruption.
Key Points
- A segmentation fault means your program tried to access forbidden memory.
- It usually happens with bad pointers or out-of-bounds array access.
- The operating system stops the program to protect memory safety.
- Careful pointer and array use helps avoid segmentation faults.