Home > Software engineering >  Why buffer overflow here
Why buffer overflow here

Time:01-28

In Bjarne Stroustrup's "The C Programming Language" there is this code

void input()
{
    int buf[max];
    int count = 0;
    for (int i; cin >> i;) {
        if (i < 0) error("unexpected negative value");
        if (cout == max) error("buffer overflow");
            buf[count  ] = i;
    }
}

followed by the author's stating that: "I assume that error() does not return; if it does, this code may cause a buffer overflow."

Why would this code cause buffer overflow if error function returns?

CodePudding user response:

Assuming the code is actually checking if (count == max) (not if (cout == max), which is nonsensical), if the error function returns, then count is equal to max at that point. buf has max valid entries, with valid indices from 0 to max - 1, so accessing buf[max] would assign to the element one past the end of the array, a trivial case of buffer overflow.

CodePudding user response:

Multiple issues with the code snippet, firstly, look at the for loop:

for (int i; cin >> i;) 

The format is supposed to be for (initializer; loop_condition; increment_statment). In your case cin >> i doesn't appear to be a valid condition that eventually terminates, so you have an infinite loop. Next let's look at the following if statement:

if (cout == max) error("buffer overflow");

The condition cout == max is never true because you're comparing a stream with an integer, and, others have identified there is a possible typo where count may have been intentional. Next, let's look at the following:

        buf[count  ] = i;

There are several issues with the above line. Firstly, although pedantic, the indentation use is misleading, since it is not connected to the if statement above. The if statement has a semicolon so this statement is not connected. Secondly, there's no guard to ensure count < max so, there's a high risk that this code will cause a buffer overrun. In fact, it was established that there was a problem with the for loop yielding in infinite cycles, so, this means that this statement can run, and, in no time at all, count will exceed max causing a guaranteed buffer overrun.

Another thing that isn't shown, is the actual definition of max. It would be helpful to confirm that it is an integer constant. In the code supplied, that context is not given.

  •  Tags:  
  • c
  • Related