Because:
Kod:
1. Arrays are fixed size.
2. C++ does not perform subscript range checking.
3. Programmers forget to check bounds, or simply assume nothing can go wrong.
4. Giving a program more data than it can handle is the number one trick in the arsenal of the hacker.
What's wrong with this code?
Kod:
int a[1000]; // Declare an array of 1000 ints
int n = 0; // number of values in a.
. . .
while (cin >> a[n]) {
n++;
}
# The additional numbers go somewhere in memory beyond the end of the array! They overwrite whatever was there...
1. Solution 1 - Check array bounds
2. Solution 2 - vectors - the correct solution
Solution 1 Explanation:
The following solution prevents subscript bounds violations, by terminating the input after 1000 input numbers without comment.
Kod:
int a[1000]; // Declare an array of 1000 ints
int n = 0; // number of values in a.
. . .
while (n < 1000 && cin >> a[n]) {
n++;
}
It would be much better to give an error message, otherwise the user will not realize the results from the program are incorrect. An improvement would be.
int temp;
Kod:
while (cin >> temp) {
if (n < 1000) {
a[n] = temp;
n++;
} else {
cerr << "ERROR: More than 1000 number input" << endl;
exit(1);
}
}
This still has problems. if we're using a GUI, we can't write to cerr. The solution to that is to throw an exception, but that example will have to wait.
Solution 2 Explanation:
Vectors (from the Standard Template Library) are an expandable array. Google Example - Vector - reverse input example for a solution to the above problems.