PROGRAMMING FUNDAMENTALS
QUIZ NO2
NAME:UZAIR ARSHAD
ROLL NO: 23014119-168
BSCS SECTION D
Date: 27/11/24
QUESTION :
Discuss bound checking problem in arrays with a coding example. Example should be different than
discussed in class.
ANSWER :
Bound Checking Problem in Arrays in C++:
C++ is a fixed-size data structure, and array indices are accessed directly without automatic bounds
checking. This can easily access memory beyond the bounds of the array, which leads to undefined
behavior. This can cause unexpected outputs, crashes, or even security vulnerabilities.
Bound Checking Problem Example
#include <iostream>
Using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int index = 10; //Index 10 is out of bounds for an array with a size of 5
cout << "Element at index " << index << " is: " << arr[index] << std::endl;
return 0;
Output :
The program could print something like this (garbage value), crashes, or won't give any output:
Element at index 10 is: 324295
Solution: Explicit Bound Checking in C++
We can avoid this problem by adding explicit bounds checking before accessing an element of an array.
Thus, we can ensure that the index falls in the valid range, and if not so, we can handle this situation
graciously.
Example:
#include <iostream>
Using namespace std:
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int index = 10; // Index 10 is past the bounds of an array of size 5
// Manual bound checking
if (index >= 0 && index < 5) {
cout << "Element at index " << index << " is: " << arr[index] << std::endl;
} else {
cout << "Error: Index " << index << " is out of bounds. Valid indices are from 0 to 4." << std::endl;
return 0;
}
Output:
Error: Index 10 is out of bounds. Valid indices are from 0 to 4.