Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
List of Common Reasons for Segmentation Faults in C/C++
The main reason for segmentation fault is accessing memory that is either not initialized, out of bounds for your program or trying to modify string literals. These may cause a segmentation fault though it is not guaranteed that they will cause a segmentation fault. Here are some of the common reasons for segmentation faults −
- Accessing an array out of bounds
- Dereferencing NULL pointers
- Dereferencing freed memory
- Dereferencing uninitialized pointers
- Incorrect use of the "&" (address of) and "*" (dereferencing) operators
- Improper formatting specifiers in printf and scanf statements
- Stack overflow
- Writing to read-only memory
Common Examples of Segmentation Faults
Example 1: Accessing Array Out of Bounds
This happens when you try to access an array element beyond its allocated size −
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
/* Accessing beyond array bounds - causes segmentation fault */
printf("Value: %d\n", arr[10]);
return 0;
}
Example 2: Dereferencing NULL Pointer
Attempting to access memory through a NULL pointer causes immediate segmentation fault −
#include <stdio.h>
int main() {
int *ptr = NULL;
/* Dereferencing NULL pointer - causes segmentation fault */
printf("Value: %d\n", *ptr);
return 0;
}
Example 3: Using Freed Memory
Accessing memory after it has been freed leads to undefined behavior and potential segmentation fault −
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*)malloc(sizeof(int));
if (ptr == NULL) return 1;
*ptr = 42;
free(ptr);
/* Using freed memory - causes segmentation fault */
printf("Value: %d\n", *ptr);
return 0;
}
Example 4: Modifying String Literals
String literals are stored in read-only memory, attempting to modify them causes segmentation fault −
#include <stdio.h>
int main() {
char *str = "Hello World";
/* Modifying string literal - causes segmentation fault */
str[0] = 'h';
printf("String: %s\n", str);
return 0;
}
Prevention Tips
- Always check array bounds before accessing elements
- Initialize pointers to NULL and check before dereferencing
- Set freed pointers to NULL to avoid accidental reuse
- Use char arrays instead of string literals when modification is needed
- Validate function parameters and return values
Conclusion
Segmentation faults are runtime errors caused by improper memory access. Understanding these common causes and following safe programming practices can help prevent most segmentation faults in C programs.
