segmentation fault can occur in C or C++ when a program tries to access memory that it doesn’t have permission for, such as accessing an array beyond its bounds. Here’s an example:
int arr[5] = {1, 2, 3, 4, 5};
printf("%d\n", arr[10]); // Accessing out of bound index
In this code, we declare an integer array
arr
with five elements. However, we attempt to print the value at the tenth index of
arr
, which is outside the allocated memory space for
arr
. This results in a segmentation fault because the program is trying to access memory not assigned to it.