10. Arrays
Index out of Bounds
Can you tell what is wrong with the following program without executing it by a computer:
#include <iostream> #include <vector> using namespace std; int main() { vector<double> data = {1, 2, 3, 4, 5}; for(int i=0; i<=5; i++) cout << data[i] << endl; }
If you are using Code::Blocks IDE, the mentioned dialogue will not be displayed. In fact, the C++ language standard does not require this error to be caught, but the Visual Studio will catch it when running in Debug mode (but not in Release mode). In order to see this error in Code::Blocks, from the main menu choose Settings->Compiler, and the Global compiler settings dialog will open. Somewhere in the middle of it there is a tab titled #defines. Select it, and then add the line containing the text _GLIBCXX_DEBUG
there. Then click the OK button. From the main menu, choose Build -> Rebuild. Then choose Build -> Run.
Now, try to execute this program just to see what the computer will make of it. An error dialogue will appear, and some text containing the words like "vector subscript out of range" may be displayed. Click the Abort button to terminate the execution of the program.
The problem is that the loop variable i
will
range from 0 to 5, while the array data
only has elements data[0]
to data[4]
. Although
element data[5]
does not exist, the program will attempt to print out this
nonexistent element, causing a failure.
The debugger can also help us to find this error. To put the debugger to work, start this program by selecting DEBUG -> Start Debugging from the menu, or by simply pressing F5. The program will crash again, but this time click on the Retry button in the error dialogue, and then on the Break button in the following dialogue. The debugger will then show the state of the program at the point where it crashed. The line of code that has caused the error will be indicated by an arrow. Finish debugging by selecting DEBUG -> Stop Debugging from the menu.
To correct this error, you just need to
replace the operator '<=
' by the operator '<
' in the for
loop.