Buffer overflow is the phrase used to describe trying to put more data into an array than there is room for.
int a[1000]; // Declare an array of 1000 ints int n = 0; // number of values in a. . . . while (cin >> a[n]) { n++; }
Answer: The additional numbers go somewhere in memory beyond the end of the array! They overwrite whatever was there. The hacker trick is to figure out where program instructions occur and supply sufficient data to overwrite the instructions. And to figure out exactly which numbers are translated into the binary codes for instructions that they want to be exectuted the next time anyone calls on the original code.
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; 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.