0 votes
in C Plus Plus by
Can you provide an example of how a Segmentation Fault might occur in C or C++?

1 Answer

0 votes
by

 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:

#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("%d\n", arr[10]); // Accessing out of bound index
return 0;
}

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.

Related questions

0 votes
asked Nov 29, 2023 in C Plus Plus by JackTerrance
0 votes
asked Nov 28, 2023 in C Plus Plus by JackTerrance
...