# C++ Notes: Arrays: Buffer Overflow

Because

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.

giving a program more data than it can handle is the number one trick in the arsenal of the hacker.

Buffer overflow is the phrase used to describe trying to put more data into an array than there is room for.

## What's wrong with this code?

Hint: What happens in the following loop if there are more than 1000 numbers in the input?

    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.

## Solution 1 - Check array bounds

The following solution prevents subscript bounds violations, by terminating the input after 1000 input numbers without comment.

    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.

## Solution 2 - vectors - the correct solution

Vectors (from the Standard Template Library) are an expandable array. Look at Example - Vector - reverse input example for a solution to the above problems.