51. Array Access Out of Bounds

#include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;

int getValue(const vector<int>& arr, int idx) {
    if (idx < 0 || idx >= (int)arr.size()) {
        throw out_of_range("Index out of range");
    }
    return arr[idx];
}

int main() {
    int n;
    cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++) cin >> arr[i];

    int idx;
    cin >> idx;

    try {
        int value = getValue(arr, idx);
        cout << "Value: " << value << "\n";
    } catch (const out_of_range& e) {
        cout << "Error: " << e.what() << "\n";
    }

    return 0;
}

Solution Details

  • If the index is invalid, throw out_of_range("Index out of range").
     
  • Otherwise, return the element at that position.
     
  • The catch (const out_of_range& e) specifically handles this error.
     

👉 In simple words:

  • Asking for arr[2] in [10, 20, 30] works fine.
  • Asking for arr[5] throws an exception and prints "Error: Index out of range".
     

Significance for Embedded Developers

  • In embedded firmware, buffer overruns can corrupt memory and cause crashes.
     
  • Safe access with proper error handling ensures robust code.
     
  • This is like ensuring you don’t read/write past the end of a UART buffer or DMA buffer.
     
Loading...

Input

5 10 20 30 40 50 2

Expected Output

Value: 30