Vector subscript out of range

Category: C++, Programming | August 11, 2023

This error occurs when attempting to access an element in a vector or array using an invalid index (e.g., a negative index or an index beyond the vector’s bounds). In this article, we’ll dig into the reasons for this error e.g., using an incorrect index value of the vector element, this small error can cause a lot of frustration. To resolve such an error, make sure you are using an index value that is within the scope of the vector element.

What is the Error?

The “Vector Subscript Out of Range” error is a common issue that happens when attempting to access an element of a vector using an index that is outside the valid range of indices for that vector. This error is typically experienced in programming language like C++ while managing arrays or vectors. When the index provided is less than zero or greater than or equal to the size of the vector, this error occurs.

Here is an example of how the error is shown:

Causes of the Error

The “Vector Subscript Out of Range” error occurs when a program attempts to access an element in a vector using an index that is outside the valid range of indices. There are various such issues that can cause the program to generate the concerned error message. The causes are mentioned below.

1. Negative Index Value

int main() {
vector  num = { 1,2,3,4,5 };
int index = -1; // Error: Negative Index Value 
// Accessing invalid index 
int value = num[index];
std::cout << "Value:" << value << std::endl;
return 0;}

In the example code above, we tried to access an element in ‘num’ vector using a negative index (‘index = -1’). 
Since index is -1, it is an out-of-range index because, the vector numbers have valid indices from 0 to size – 1, where size is the number of elements in the vector. Attempting to access an element with an out-of-range index causes the “Vector subscript out-of-range” error.

2. Index Value beyond Vector’s Bound 

int main() {
vector  num = { 1,2,3,4,5 };
int index = 7; // Error: Index Value beyond vector's bound 
// Accessing invalid index 
int value = num[index];
std::cout << "Value:" << value << std::endl;
return 0;}

In the example code above, we tried to access an element in ‘num’ vector using an index value beyond vector’s scope (‘index = 7’).
The vector ‘num’ has valid indices from 0 to size – 1, where size is the number of elements in the vector (‘num’ has 5 elements with valid indices from 0 to 4). Attempting to access an element with an out of range index (in this case,index= 7) causes the “Vector subscript out-of-range” error. 

Solutions to Fix the Error 

Consider the following methods to prevent the “Vector subscript out-of-range” error.

1. Using Valid Index Values

Ensure that the index used to access vector elements is within the valid range (0 to size-1)

int main() {
vector  num = { 1,2,3,4,5 };
int index = 7; // Error: Index Value beyond vector's bound 
int value = num[index];std::cout << "Value:" << value << std::endl;
}

To fix this, use index value within the vector elements.

int main() {
vector  num = { 1,2,3,4,5 };
int index = 2;  // Valid Index Number
int value = num[index];
std::cout << "Value:" << value << std::endl;
}

The above code initializes a vector named ‘num’ with integers {1, 2, 3, 4, 5}. The index variable index is set to 2, which is a valid index within the range 0 to size – 1 (the vector has 5 elements, so valid indices are from 0 to 4). The program then accesses the element at index 2, which is 3, and prints the value as Value: 3. By using a valid index, we ensure that the code is correct and the error is fixed.

Caution: Using invalid indices can lead the program to crash and perform undefinable behavior.

2. Perform Boundary Checks

Before accessing an element of the vector, we must perform boundary checks to make sure the index is inside the valid range in order to prevent problems.

int main() {
vector  num = { 1,2,3,4,5 };
int index = 7;
// Perform boundary check before accessing elements
if (index > 0 && index < num.size) {
int value = num[index];
std::cout << "Value:" << value << std::endl;
}
else {
std::cout << "Invalid Index. " << std::endl;
}
return 0;
}

The above code initializes a vector named ‘num’ with integers {1, 2, 3, 4, 5}. The index variable index is set to -1, which is an invalid index since vector indices must not be negative.
Before debugging, the program checks if index is within the valid range (0 to num.size() – 1). Since -1 is outside this range, the boundary check evaluates to false, and the program prints “Invalid index”. This approach ensures that the code handles out-of-range cases effectively, avoiding the error and providing an appropriate feedback when accessing vector elements.

Use try-catch for Error Handling

To resolve the out-of-range exception, use a try-catch block.

int main() {
vector  num = { 1,2,3,4,5 };
int index = 7; // Index value beyond vector's bound
try {
// Attempt to access an element
int value = num.at(index);
std::cout << "Value: " << value << std::endl;
}
catch (const out_of_range & e) {
std::cout << "Exception: " << e.what() << std::endl;
}
}

The above code initializes a vector named ‘num’ with integers {1, 2, 3, 4, 5}. The index variable index is set to 7, which is an invalid index since the vector has only five elements .
Inside the try block, we attempt to access an element at index 7 using the at() function. However, since the index is out of range, an out_of_range exception is thrown. The catch block catches this exception, and we print an informative message, such as “Exception: vector::_M_range_check: __n (which is 7) >= this->size() (which is 5)“.
Using the try-catch block prevents the program from crashing due to the out-of-range access, allowing us to handle the error more gracefully and providing useful information about the exception for debugging and error handling purposes.

Conclusion

In conclusion, the “Vector subscript out-of-range” error is a common issue that occurs when attempting to access vector elements with invalid indices. This error can lead to program crashes and unexpected behaviour. To resolve this error, we can employ various solutions, such as using valid index values within the vector’s bounds, performing boundary checks before accessing elements, or using try-catch blocks to catch out-of-range exceptions. These solutions ensure the code runs smoothly and handles potential errors.