I’m getting a segmentation fault in my C++ program when trying to access an array element. Here’s my code:

#include <iostream>
using namespace std;

int main() {
    int arr[5];
    cout << arr[10]; // Accessing out-of-bounds index
    return 0;
}

How can I prevent this memory access issue?

Thanks for the MVE (minimum viable example).
But it's just bad code. c, c++ and a lot of language won't stop you from going out of bounds.

You’re creating an array of 5 integers and then trying to access the 11th integer in the array (assuming the indexes start at 0). You’re getting an out of bounds error because you’re trying to access an array element that doesn’t exist. You can access arr[0] up through arr[4].

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.